0
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
}

Is there any other way rather than calling eval to invoke methods which are elements of an array?

canoe
  • 1,273
  • 13
  • 29

2 Answers2

5

Using Object#send:

methods.each { |m| Shop.send(m) }
tokland
  • 66,169
  • 13
  • 144
  • 170
2

Yes, possible using Method#call method :

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) will give you an object of the class Method, now you can invoke the method #call on that method object.

Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317