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,165
  • 11
  • 25

2 Answers2

5

Using Object#send:

methods.each { |m| Shop.send(m) }
tokland
  • 63,578
  • 13
  • 136
  • 167
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
  • 113,563
  • 27
  • 250
  • 306