1

Is there a way to transform a symbol to a method call? I know it's possible for a String, but not for a symbol. I have this code in conveyance.rb:

def boats
  boats = []
  User.all.each{ |u| boats += u.boats}
  boats
end
def boats_nb
  self.boats.length
end
def cars
  cars = []
  User.all.each{ |u| cars += u.cars}
  cars
end
def cars_nb
  self.cars.length
end

I would like to know if there is a means to make a method like that:

def conveyances(:symb)
  c = []
  User.all.each{ |u| c += u.to_method(:symb) }
  c
end
def conveyances_nb(:symb)
  User.to_method(:symb).length
end
sawa
  • 165,429
  • 45
  • 277
  • 381
Jérémy Pouyet
  • 1,989
  • 6
  • 28
  • 55

2 Answers2

8

You could use Object#public_send method:

def conveyqnces_nb(symb)
  User.public_send(symb).length
end

or, if you would like, Object#send might be suitable. The difference is that send allows to call private and protected methods, while public_send acts as typical method call - it raises an error if method is private or protected and the caller object isn't allowed to call it.

Marek Lipka
  • 50,622
  • 7
  • 87
  • 91
4

Use the #send instance method

u.send(:symb)
cpjolicoeur
  • 12,766
  • 7
  • 48
  • 59