Given a simple code in file test.rb:
def todo_list(todo_selector)
library = ["Get a cat", "Get a dog", "Build a fighting ring"]
puts "Your current step in todo-list is:\n#{library[todo_selector]}"
end
ARGV.each { |todo| todo_list(todo_selector) }
How am I able to call this method with an index via command line?
Normally I would use test.rb 1, but I am getting this error:
Traceback (most recent call last):
2: from test.rb:17:in `<main>'
1: from test.rb:17:in `each'
test.rb:17:in `block in <main>': undefined local variable or method `todo_selector' for main:Object (NameError)
Did you mean? todo_list
What am I doing wrong?
Try this way for one element, take care to convert String into Integer in order to access the Array by index.
selector = ARGV[0].to_i
todo_list(selector)
For an array of arguments: ARGV.each{ |i| todo_list(i.to_i) }
Related
I noticed that attempting to use the send method while passing in unpacked keyword args as a variable led to some unexpected behavior.
First the setup:
class SomeClass
def some_method
true
end
end
kwargs = {}
c = SomeClass.new
c.some_method
=> true
c.some_method(**kwargs)
=> true
c.send(:some_method, **{})
=> true
All of the above works as expected. However, if I attempt to use send in conjunction with passing key word args via a variable (as oppose to a literal), I suddenly get a 'wrong number of arguments' error
c.send(:some_method, **kwargs)
Traceback (most recent call last):
5: from /Users/rs/.rvm/rubies/ruby-2.6.7/bin/irb:23:in `<main>'
4: from /Users/rs/.rvm/rubies/ruby-2.6.7/bin/irb:23:in `load'
3: from /Users/rs/.rvm/rubies/ruby-2.6.7/lib/ruby/gems/2.6.0/gems/irb-1.0.0/exe/irb:11:in `<top (required)>'
2: from (irb):9
1: from (irb):2:in `some_method'
ArgumentError (wrong number of arguments (given 1, expected 0))
Is this intended behavior?
I'm getting the error undefined local variable or method '_1' for main:Object when I run the following code. Any idea why I'm getting this error? and how can I store the result in a variable.
result="-e hostname=webserver001 -e username=root -e password=testing123"
p result.scan(/\w+=\w+/)
.map { _1.split("=") }
.to_h
Error:
Traceback (most recent call last):
2: from main.rb:4:in `<main>'
1: from main.rb:4:in `map'
main.rb:4:in `block in <main>': undefined local variable or method `_1' for main:Object (NameError)
exit status 1
You're probably running an older version of ruby - the numbered parameters for blocks have been available in ruby since 2.7 - see https://www.bigbinary.com/blog/ruby-2-7-introduces-numbered-parameters-as-default-block-parameters
You can make it work on older version by using
p result.scan(/\w+=\w+/)
.map { |s| s.split("=") }
.to_h
require_relative 'json_lookup'
require_relative 'csv_lookup'
require_relative 'error'
BASE_RATE = 'EUR'
class CurrencyExchange
def initialize(file:, date:, from:, to:)
#file = file
#date = date
#from = from
#to = to
end
def rate
lookup = find_lookup
lookup.to_currency / lookup.from_currency
end
private
def find_lookup
case File.extname(#file)
when ".json"
JsonLookup.new(#file, #date, #from, #to)
when ".csv"
CsvLookup.new(#file, #date, #from, #to)
else raise FileError
end
end
end
I keep on getting this error for when i run the CurrencyExchange.rate in irb so I am guessing something is going wrong with the rate method but can't figure it out as to why. But I may be missing something completely obvious... As I am a complete beginner at Ruby, would appreciate any help :)
The traceback is as follows..
irb(main):003:0> CurrencyExchange.rate(Date.new(2018, 11, 22), "USD", "GBP") Traceback (most recent call last):
5: from C:/Ruby26-x64/bin/irb.cmd:31:in `<main>'
4: from C:/Ruby26-x64/bin/irb.cmd:31:in `load'
3: from C:/Ruby26-x64/lib/ruby/gems/2.6.0/gems/irb-1.0.0/exe/irb:11:in `<top (required)>'
2: from (irb):3
1: from (irb):3:in `rescue in irb_binding'
NoMethodError (undefined method `rate' for CurrencyExchange:Class)
rate is an instance method in your example but CurrencyExchange.rate tries to call a class method.
To solve this, initialize an instance first and call then rate on that instance. Furthermore rate doesn't accept arguments, you need to pass the variables to the initializing method.
currency_exchange = CurrencyExchange.new(
file: file, date: Date.new(2018, 11, 22), from: "USD", to: "GBP"
)
currency_exchange.rate
Note take the initializer expects 4 named arguments. You will need to pass a file to the new method too.
I have a ruby script as following:
class HashSet < Hash
def initialize
super { |hash, key| hash[key] = Set.new }
end
end
data = {}
data["hash"] ||= HashSet.new
data["hash"]["colors"].add "blue"
puts data
An error is raised when run this script:
$ ruby demo.rb
Traceback (most recent call last):
2: from demo.rb:9:in `<main>'
1: from demo.rb:9:in `[]'
demo.rb:3:in `block in initialize': uninitialized constant HashSet::Set (NameError)
But when I run it with irb, it runs well:
$ irb -r ./demo.rb
{"hash"=>{"colors"=>#<Set: {"blue"}>}}
What makes the difference and how can I fix the script?
Add this to the top of your script:
require "set"
Explanation:
Set is not part of the ruby core library. Rather, it is part of the ruby standard library.
In order to use Set, you must - somewhere - require the library explicitly.
As it happens, irb actually already requires set as part of its initialisation process:
$ irb
irb(main):001:0> Set
=> Set
$ ruby -e 'Set'
Traceback (most recent call last):
-e:1:in `<main>': uninitialized constant Set (NameError)
This is the code:
def self.scrape_shoe
#doc.css("div.product-card__body").each do |nike|
name = nike.css("div.product-card__title").text.strip
price = nike.css("div.product-card__price").text.strip
shoes = self.new
#all << shoes #having error here
end
end
This is the error:
Traceback (most recent call last):
7: from bin/new_nikes:7:in `<main>'
6: from /home/merkonical/new_nikes/lib/new_nikes/cli.rb:17:in `call'
5: from /home/merkonical/new_nikes/lib/new_nikes/cli.rb:11:in `list_price'
4: from /home/merkonical/new_nikes/lib/new_nikes/scraper.rb:9:in `scrape_shoe'
3: from /home/merkonical/.rvm/gems/ruby-2.6.1/gems/nokogiri-1.10.4/lib/nokogiri/xml/node_set.rb:237:in `each'
2: from /home/merkonical/.rvm/gems/ruby-2.6.1/gems/nokogiri-1.10.4/lib/nokogiri/xml/node_set.rb:237:in `upto'
1: from /home/merkonical/.rvm/gems/ruby-2.6.1/gems/nokogiri-1.10.4/lib/nokogiri/xml/node_set.rb:238:in `block in each'
/home/merkonical/new_nikes/lib/new_nikes/scraper.rb:13:in `block in scrape_shoe': undefined method `<<' for nil:NilClass (NoMethodError)
What are possible fixes I can do for this?
I am working on Ruby
What are possible fixes I can do for this?
#all is nil. nil doesn't have a method named <<. Make sure #all is not nil.
Getting error because you are pushing shoes object into undefined instance variable.
Define #all in action.
def self.scrape_shoe
#doc.css("div.product-card__body").each do |nike|
#all = []
name = nike.css("div.product-card__title").text.strip
price = nike.css("div.product-card__price").text.strip
shoes = self.new
#all << shoes #having error here
end
end
Hope this helps you