class Shop
def self.name
"kids-toy"
end
def self.postcode
1000
end
end
methods = ["name", "postcode"]
methods.each {|m|
mcall = "Shop.#{m}"
eval mcall
}
还有其他方法而不是调用eval
来调用作为数组元素的方法吗?
答案 0 :(得分:5)
使用Object#send:
methods.each { |m| Shop.send(m) }
答案 1 :(得分:2)
是的,可以使用Method#call
方法:
class Shop
def self.name
"kids-toy"
end
def self.postcode
1000
end
end
methods = ["name", "postcode"]
methods.each do |m|
p Shop.method(m).call
end
# >> "kids-toy"
# >> 1000
Shop.method(m)
将为您提供类Method
的对象,现在您可以在该方法对象上调用方法#call
。