When I do require './primes.rb' in irb I get this:
1.9.3-p392 :004 > require './primes.rb'
LoadError: cannot load such file -- ./primes.rb
from /Users/RBonhardt/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from /Users/RBonhardt/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from (irb):4
from /Users/RBonhardt/.rvm/rubies/ruby-1.9.3-p392/bin/irb:16:in `<main>'
Here is the primes.rb document:
# primes.rb
require 'debugger'
def prime?(num)
debugger
(1..num).each do |i|
if (num % i) == 0
return false
end
end
end
def primes(num_primes)
ps = []
num = 1
while ps.count < num_primes
primes << num if prime?(num)
end
end
if __FILE__ == $PROGRAM_NAME
puts primes(100)
end
Any suggestions of how to get this to work would be greatly appreciated!
When I do require relative it gives me this:
1.9.3-p392 :010 > require_relative 'primes.rb'
LoadError: cannot infer basepath
from (irb):10:in `require_relative'
from (irb):10
from /Users/RBonhardt/.rvm/rubies/ruby-1.9.3-p392/bin/irb:16:in `<main>'
When I do the second solution below it gives me this:
1.9.3-p392 :013 > $LOAD_PATH << "."
=> ["/Users/RBonhardt/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/site_ruby/1.9.1", "/Users/RBonhardt/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/site_ruby/1.9.1/x86_64-darwin11.4.2", "/Users/RBonhardt/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/site_ruby", "/Users/RBonhardt/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/vendor_ruby/1.9.1", "/Users/RBonhardt/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/vendor_ruby/1.9.1/x86_64-darwin11.4.2", "/Users/RBonhardt/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/vendor_ruby", "/Users/RBonhardt/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/1.9.1", "/Users/RBonhardt/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/1.9.1/x86_64-darwin11.4.2", "."]
1.9.3-p392 :014 > require 'primes.rb'
LoadError: cannot load such file -- primes.rb
from /Users/RBonhardt/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from /Users/RBonhardt/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from (irb):14
from /Users/RBonhardt/.rvm/rubies/ruby-1.9.3-p392/bin/irb:16:in `<main>'
1.9.3-p392 :015 >
When I try it in pry:
[4] pry(main)> require_relative 'primes.rb'
LoadError: cannot infer basepath
from (pry):2:in `require_relative'
[5] pry(main)> require 'primes.rb'
LoadError: cannot load such file -- primes.rb
from /Users/RBonhardt/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
[6] pry(main)> .ls
Applications Movies git-completion.bash
Desktop Music rails_projects
Documents Pictures ruby
Downloads Public runwithfriends
Dropbox code shopify
Library dev sites
[7] pry(main)> require 'ruby/app_acad_mini_curriculum/debugging/primes.rb'
LoadError: cannot load such file -- ruby/app_acad_mini_curriculum/debugging/primes.rb
from /Users/RBonhardt/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
Try require_relative
require_relative 'primes.rb'
EDIT:
Note that this will only work from within a script. If you are trying to require this script into an irb session then you will need to provide the full path to primes.rb. The reason is where irb's location is. For instance, try Dir.pwd inside irb and you will see where require_relative is attempting to search for primes.rb.
There are a couple things you could do:
# Just need to require the one file.
require_relative File.join('users', 'yourusername', 'prime_folder', 'prime.rb')
# Many files in the same folder
$LOAD_PATH << File.join('users', 'yourusername', 'prime_folder')
require 'prime.rb'
require 'another_file.rb'
Another option, one that I use, is Pry. It is like irb and is very easy to call from a script. It is a gem so:
gem install pry
At the end of your script, you could do:
if $0 == __FILE__
require 'pry'
binding.pry
end
You would then drop into an irb like REPL where you can test and debug your methods. I can't survive without it.
unlike ruby 1.8, you can't require a file that is in the same folder, because the current folder is not on the load path any longer.
To emulate the behavior of ruby 1.8, you could try
$LOAD_PATH << "."
require 'primes.rb'
However, the correct way to do in ruby 1.9, as #CharlesCaldwell pointed, is using relative_require.
Here is a good discussion of the best way to deal with this.
note that relative_require does not work in irb. You can check the motive on #CharlesCaldwell answer.
But looking in your task question, you should not use irb, you should use pry:
We're going to use two gems. One is called Pry, which is a replacement for irb. You'll have to gem install pry. It's not essential for debugging that you use Pry, but it will make life nicer.
Here is an example using relative require:
[fotanus#thing ~]$ cat primes.rb
# primes.rb
def prime?(num)
(1..num).each do |i|
if (num % i) == 0
return false
end
end
end
def primes(num_primes)
ps = []
num = 1
while ps.count < num_primes
primes << num if prime?(num)
end
end
if __FILE__ == $PROGRAM_NAME
puts primes(100)
end
[fotanus#thing ~]$ cat a.rb
require_relative 'primes.rb'
[fotanus#thing ~]$ ruby a.rb
Related
I have a file Word.rb
class Word
attr_accessor :word, :letters
def initialize (word)
##word = word
#letters = word.split('').map{|letter| {:letter => letter, :hidden => true} }
end
end
and another file Game.rb, which will use Word.rb
require_relative ('./Word.rb')
require 'pry'
class Game
attr_accessor :guesses, :guessed_letters, :words, :current_word
def initialize (words)
#guesses = 0
#guessed_letters = []
#words = words
#current_word = current_word
end
end
And I'm getting the following error:
NameError: uninitialized constant Game
When I try to create a instance of Game like this:
game = Game.new(['hello', 'sunshine', 'chipmunk', 'twitch'])
I just am not sure what I am doing wrong since I am requiring the Word.rb file that Game.rb will need. All files are on the same level, nothing is in a subdirectory. Interestingly, I do not get this error once I comment the require_relative line out (but of course, I need that file required). I have also tried not using require_relative and simply using require as well as a couple other varieties: parens/no parens, file extension/no file extension, etc. How do I properly require this file? I also have a lovely and robust array of words sitting in another file that I would like to require to be used and passed into Game.new().
Look What I did
$ mkdir test
$ cd test
$ gedit Word.rb
# and copied your content and saved
$ gedit Game.rb
# and copied you content and saved
$ irb
After IRB session run I did following
2.1.1 :001 > game = Game.new(['asd'])
NameError: uninitialized constant Game
from (irb):1
from /home/shiva/.rvm/rubies/ruby-2.1.1/bin/irb:11:in `<main>'
2.1.1 :002 > require 'game'
LoadError: cannot load such file -- game
2.1.1 :004 > require 'Game.rb'
LoadError: cannot load such file -- Game.rb
2.1.1 :005 > require './Game.rb'
=> true
2.1.1 :006 > game = Game.new(['shiva', 'bhusal'])
=> #<Game:0x00000003085428 #guesses=0, #guessed_letters=[], #words=["shiva", "bhusal"], #current_word=nil>
2.1.1 :007 >
Try like this
So I am simply trying to run this code below with sunlight congress gem, but I seem to be doing something wrong. I am trying to include the gem in the project however something is off.
I am trying to implement this using RubyMine 7.1.2(if version matters), Ruby 2.2.2.
sunlight congress can be found here: https://github.com/sunlightlabs/ruby-sunlight.
Also, I am working on windows 8.1.
require 'csv'
require 'sunlight-congress'
require 'erb'
Sunlight::Congress.api_key = "e179a6973728c4dd3fb1204283aaccb5"
def neat_zip(zipcode)
zipcode.to_s.rjust(5,"0")[0..4]
end
def legislator_by_zip(zipcode)
Sunlight::Congress::Legislator.by_zipcode(zipcode)
end
def save_thank_you_letters(id,form_letter)
Dir.mkdir("output") unless Dir.exists?("output")
filename = "output/thanks_#{id}.html"
File.open(filename,'w') do |file|
file.puts form_letter
end
end
puts "EventManager initialized."
contents = CSV.open 'event_attendees.csv', headers: true, header_converters: :symbol
template_letter = File.read "form_letter.erb"
erb_template = ERB.new template_letter
contents.each do |row|
id = row[0]
name = row[:first_name]
zipcode = neat_zip(row[:zipcode])
legislators = legislator_by_zip(zipcode)
form_letter = erb_template.result(binding)
save_thank_you_letters(id,form_letter)
end
I am getting this error:
C:\Ruby22\bin\ruby.exe -e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) C:/Ruby22/event_manager/sunlight-congress-master/lib/event_manager.rb
C:/Ruby22/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require': cannot load such file -- sunlight-congress (LoadError)
from C:/Ruby22/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
from C:/Ruby22/event_manager/sunlight-congress-master/lib/event_manager.rb:2:in `<top (required)>'
from -e:1:in `load'
from -e:1:in `<main>'
Do i simply have the path wrong? gem isnt installed?
You need to gem install sunlight-congress.
Update: Resources to install gems in Windows / RubyMine
Installing gems with RubyMine
Installing Ruby Gem in Windows
http://rubyinstaller.org/
I have the following 2 files in the same dir:
churn.rb:
subsystem_names = ['audit', 'fulfillment', 'persistence',
'ui', 'util', 'inventory']
start_date = month_before(Time.now)
puts header(start_date)
subsystem_names.each do | name |
puts subsystem_line(name, change_count_for(name))
end
churn_test.rb:
require "test/unit"
require "churn"
class ChurnTests < Test::Unit::TestCase
def test_month_before_is_28_days
assert_equal(Time.local(2005, 1, 1),
month_before(Time.local(2005, 1, 29)))
end
end
When I run churn_test.rb I get the following error:
/Users/ca/.rbenv/versions/2.1.1/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- churn (LoadError)
from /Users/ca/.rbenv/versions/2.1.1/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from churn-tests.rb:8:in `<main>'
When you require sth, Ruby searches the source in $LOAD_PATH ($:). For security concern, the current working directory is not included in $LOAD_PATH. You can either explicitly add the directory into $LOAD_PATH
$: << File.dirname(__FILE__)
require 'churn'
or use the Kernel#require_relative to require a module based on the same directory:
require_relative "churn"
This program
require 'em-synchrony' ## v1.0.0
require 'em-hiredis' ## v0.1.0
module EventMachine
module Hiredis
class Client
def self.connect(host = 'localhost', port = 6379)
conn = new(host, port)
EM::Synchrony.sync conn.connect
conn
end
alias :old_method_missing :method_missing
def method_missing(sym, *args)
EM::Synchrony.sync old_method_missing(sym, *args)
end
end
end
end
EventMachine.synchrony do
redis = EM::Hiredis.connect
redis.set('foo', 'bar')
puts redis.get('foo')
EM.stop
end
dies like this
$ ruby /tmp/reddy.rb
/home/blt/.rvm/gems/ruby-1.9.3-p0/gems/em-synchrony-1.0.0/lib/em-synchrony.rb:58:in `yield': can't yield from root fiber (FiberError)
from /home/blt/.rvm/gems/ruby-1.9.3-p0/gems/em-synchrony-1.0.0/lib/em-synchrony.rb:58:in `sync'
from /tmp/reddy.rb:16:in `method_missing'
from /home/blt/.rvm/gems/ruby-1.9.3-p0/gems/em-hiredis-0.1.0/lib/em-hiredis/client.rb:119:in `select'
from /home/blt/.rvm/gems/ruby-1.9.3-p0/gems/em-hiredis-0.1.0/lib/em-hiredis/client.rb:38:in `block in connect'
from /home/blt/.rvm/gems/ruby-1.9.3-p0/gems/em-hiredis-0.1.0/lib/em-hiredis/event_emitter.rb:8:in `call'
from /home/blt/.rvm/gems/ruby-1.9.3-p0/gems/em-hiredis-0.1.0/lib/em-hiredis/event_emitter.rb:8:in `block in emit'
from /home/blt/.rvm/gems/ruby-1.9.3-p0/gems/em-hiredis-0.1.0/lib/em-hiredis/event_emitter.rb:8:in `each'
from /home/blt/.rvm/gems/ruby-1.9.3-p0/gems/em-hiredis-0.1.0/lib/em-hiredis/event_emitter.rb:8:in `emit'
from /home/blt/.rvm/gems/ruby-1.9.3-p0/gems/em-hiredis-0.1.0/lib/em-hiredis/connection.rb:15:in `connection_completed'
from /home/blt/.rvm/gems/ruby-1.9.3-p0/gems/eventmachine-1.0.0.beta.4/lib/eventmachine.rb:179:in `run_machine'
from /home/blt/.rvm/gems/ruby-1.9.3-p0/gems/eventmachine-1.0.0.beta.4/lib/eventmachine.rb:179:in `run'
from /home/blt/.rvm/gems/ruby-1.9.3-p0/gems/em-synchrony-1.0.0/lib/em-synchrony.rb:27:in `synchrony'
from /tmp/reddy.rb:22:in `<main>'
I find this deeply confusing. Why doesn't it work and am I at fault? If so, what can I do differently? Unless I've glossed over something, this is kosher, per the em-synchrony README.
I think your code can work if you find the correct version of em-hiredis it is trying to monkey patch, that is one problem with loose dependencies.
Here is a fully working code but based on the master branch of em-synchrony:
Gemfile:
source :rubygems
gem 'em-synchrony', :git => "git://github.com/igrigorik/em-synchrony.git"
gem 'em-hiredis', '~> 0.1.0'
test.rb:
require 'rubygems'
require 'bundler/setup'
require 'em-synchrony'
require 'em-synchrony/em-hiredis'
EventMachine.synchrony do
redis = EM::Hiredis.connect
redis.set('foo', 'bar')
puts redis.get('foo')
EM.stop
end
and then run it with:
$ bundle
$ ruby test.rb
Monkey patching is an inherently flawed way of patching gems unless you ensure the exact version of the gem you patched is used which is something em-synchrony should enforce or at least detect.
I'm packaging my library into gem. This is the structure of the project.
|~lib/
| |~renren_api/
| | |-authentication.rb
| | |-http_adapter.rb
| | \-signature_calculator.rb
| \-renren_api.rb
|+spec/
|-README
\-renren-api.gemspec
I write the "lib/renren-api.rb" as follow. Rack inspire me.
module RenrenAPI
VERSION = [0, 3, 1]
def self.version
VERSION * "."
end
autoload :Authentication, "renren_api/authentication"
autoload :SignatureCalculator, "renren_api/signature_calculator"
autoload :HTTPAdapter, "renren_api/http_adapter"
end
Why the autoload method cannot find the required file, but Rack's can?
ruby-1.9.2-head :001 > require "renren_api"
=> true
ruby-1.9.2-head :002 > RenrenAPI::Authentication
LoadError: no such file to load -- renren_api/authentication
from (irb):2
from /Users/siegfried/.rvm/rubies/ruby-1.9.2-head/bin/irb:16:in `<main>'
ruby-1.9.2-head :003 > RenrenAPI::HTTPAdapter
LoadError: no such file to load -- renren_api/http_adapter
from (irb):3
from /Users/siegfried/.rvm/rubies/ruby-1.9.2-head/bin/irb:16:in `<main>'
# The following split into newlines to make more readable
ruby-1.9.2-head :004 > $:
=> ["/Users/siegfried/.rvm/gems/ruby-1.9.2-head/gems/renren-api-0.3.1/lib",
"/Users/siegfried/.rvm/rubies/ruby-1.9.2-head/lib/ruby/site_ruby/1.9.1",
"/Users/siegfried/.rvm/rubies/ruby-1.9.2-head/lib/ruby/site_ruby/1.9.1/x86_64-darwin10.6.0",
"/Users/siegfried/.rvm/rubies/ruby-1.9.2-head/lib/ruby/site_ruby",
"/Users/siegfried/.rvm/rubies/ruby-1.9.2-head/lib/ruby/vendor_ruby/1.9.1",
"/Users/siegfried/.rvm/rubies/ruby-1.9.2-head/lib/ruby/vendor_ruby/1.9.1/x86_64-darwin10.6.0",
"/Users/siegfried/.rvm/rubies/ruby-1.9.2-head/lib/ruby/vendor_ruby",
"/Users/siegfried/.rvm/rubies/ruby-1.9.2-head/lib/ruby/1.9.1",
"/Users/siegfried/.rvm/rubies/ruby-1.9.2-head/lib/ruby/1.9.1/x86_64-darwin10.6.0"]
My gemspec file is as follow.
Gem::Specification.new do |spec|
spec.name = "renren-api"
spec.version = "0.3.1"
spec.summary = "a library to request Renren's API"
spec.description = <<-EOF
renren-api provides capability to request the service of Renren Social Network.
EOF
spec.files = Dir["{lib/*,spec/*}"] + %w{README}
spec.require_path = "lib"
spec.extra_rdoc_files = %w{README}
spec.test_files = Dir["spec/*_spec.rb"]
spec.author = "Lei, Zhi-Qiang"
spec.email = "#my email"
spec.homepage = "https://github.com/siegfried/renren-api"
end
When require "renren_api/authentication".
ruby-1.9.2-head :001 > require "renren_api/authentication"
LoadError: no such file to load -- renren_api/authentication
from <internal:lib/rubygems/custom_require>:29:in `require'
from <internal:lib/rubygems/custom_require>:29:in `require'
from (irb):1
from /Users/siegfried/.rvm/rubies/ruby-1.9.2-head/bin/irb:16:in `<main>'
Add ".rb" will not help.
ruby-1.9.2-head :001 > require "renren_api"
=> true
ruby-1.9.2-head :002 > RenrenAPI::Authentication
LoadError: no such file to load -- renren_api/authentication.rb
from (irb):2
from /Users/siegfried/.rvm/rubies/ruby-1.9.2-head/bin/irb:16:in `<main>'
I find the problem is I made a wrong gemspec.
spec.files = Dir["{lib/*,spec/*}"] + %w{README}
It didn't package the file under "lib/renren_api/".
To change it like this will solve this problem.
spec.files = Dir["{lib/**/*,spec/*}"] + %w{README}