この質問に対する答えをしばらく探していましたが、理解して適用できる答えを見つけることができませんでした。
@brand、@setup、およびの 3 つのインスタンス変数を含むクラスがあり@yearます。そのクラスに含まれるモジュールがあります。このモジュールには、、、、および関連する変数に割り当てられた値を出力するだけの3 つのメソッドがprint_brand()あります。print_setup()print_year()
ユーザーから 2 つの文字列を取得し、最初の文字列をオブジェクト名として使用し、2 番目の文字列をメソッド名として使用したいと考えています。これが私が今持っているものです:
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)
b文字列からオブジェクト名に変換する機能がいくつかありません。たとえば、ユーザーが「trance」と入力してから「print_year」と入力し、「2011」を画面に表示できるようにしたいと考えています。constantizeonを使用しようとしましbたが、うまくいかないようです。エラーが発生します:
in 'const_defined?': wrong constant name trance (NameError)
他のアイデアはありますか?