I've been looking for an answer to this question for a while, but I haven't been able to find one that I was able to understand and apply.
I have a class that contains three instance variables: @brand, @setup, and @year. I have a module, included in that class, that has three methods: print_brand(), print_setup(), and print_year() that simply print the value assigned to the associated variable.
I'd like to get two strings from a user and use the first as an object name and the second as a method name. Here's what I have right now:
class Bike
include(Printers)
def initialize(name, options = {})
@name = name
@brand = options[:brand]
@setup = options[:setup]
@year = options[:year]
end
end
trance = Bike.new("trance x3", {
:brand => "giant",
:setup => "full sus",
:year => 2011
}
)
giro = Bike.new("giro", {
:brand => "bianchi",
:setup => "road",
:year => 2006
}
)
b2 = Bike.new("b2", {
:brand => "felt",
:setup => "tri",
:year => 2009
}
)
puts "Which bike do you want information on?"
b = gets()
b.chomp!
puts "What information are you looking for?"
i = gets()
i.chomp!
b.send(i)
I'm missing some functionality that converts b from a string to an object name. For example, I want the user to be able to type in "trance" and then "print_year" and have "2011" printed on the screen. I tried to use constantize on b, but that doesn't seem to work. I get the error:
in 'const_defined?': wrong constant name trance (NameError)
Any other ideas?
b.send(i), that assumes thatbis an object that has whateveriis set to as a method. Ifbis a specific bike type, where's the object whose name is that bike type? Your bike types are variables that are instances ofBike. This seems like a complex way of providing data to a user based upon a query.