class Person
def sampleMethod
end
end
jack = Person.new
input = gets.chomp如何通过用户输入调用jack对象?我试过这个:
input = gets.downcase.chomp.to_sym它调用方法但调用对象。
我也试过这个:
eval input + '.sampleMethod'这是:
Kernel.const_get(input).sampleMethod请帮帮忙。
发布于 2015-05-23 17:33:11
我会将每个人存储在一个散列中,其中哈希的键是可以引用的名称。
class Person
Registry = {}
def sample_method
puts 'hello, world'
end
end
Person::Registry['jack'] = Person.new
name = 'jack' # or you can use: name = gets.chomp
person = Person::Registry.fetch(name)
person.sample_method在用户输入时使用eval是危险的,因为它为用户提供了各种可能意外或恶意地破坏您的程序的方法。我不会把eval作为解决这个相对简单问题的第一个工具。
发布于 2015-05-23 17:14:08
class Person
def sampleMethod
puts "hello, world"
end
end
jack = Person.new
input = "jack"您可以使用eval调用对象。
eval input
=> #<Person:0x007f916ba16c20>
eval input + ".sampleMethod"
hello, world
=> nil
jack.object_id
=> 70131276363280
(eval input).object_id
=> 70131276363280它们具有相同的对象id,因此它们调用相同的对象。
https://stackoverflow.com/questions/30415312
复制相似问题