Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 方法调用的符号_Ruby - Fatal编程技术网

Ruby 方法调用的符号

Ruby 方法调用的符号,ruby,Ruby,有没有办法将符号转换为方法调用?我知道可以用字符串,但不能用符号。我在transportation.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

有没有办法将符号转换为方法调用?我知道可以用字符串,但不能用符号。我在
transportation.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
我想知道是否有一种方法可以制作这样的方法:

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
使用#send instance方法

u.send(:symb)
使用#send instance方法

u.send(:symb)
您可以使用以下方法:

或者,如果你愿意的话,可能是合适的。区别在于
send
允许调用私有和受保护的方法,而
public\u send
充当典型的方法调用-如果方法是私有或受保护的,并且不允许调用方对象调用它,则会引发错误

您可以使用以下方法:

或者,如果你愿意的话,可能是合适的。区别在于
send
允许调用私有和受保护的方法,而
public\u send
充当典型的方法调用-如果方法是私有或受保护的,并且不允许调用方对象调用它,则会引发错误