ruby send call 的简单使用

refer: ruby on rails - What does .call do? - Stack Overflow

Ruby使用call 可以调用方法或者proc

复制代码
m = 12.method("+")
# => `method` gets the `+` method defined in the `Fixnum` instance
# m.class 
# => Method

m.call(3)    #=> 15
# `3` is passed inside the `+` method as argument 
m.call(20)   #=> 32

send方法也可以调用方法,在本地写一个测试:

复制代码
def say_hi

  puts "hihi"

end

def say_goodbye

  puts "goodbye"

end

# 使用send方式调用方法

name = "say_hi"

send(name)

m = 12.method("+")

# => `method` gets the `+` method defined in the `Fixnum` instance

# m.class

# => Method

m.call(3)    #=> 15

puts m.call(3)

# `3` is passed inside the `+` method as argument

m.call(20)   #=> 32

puts m.call(20)

运行:ruby hi.rb

得到输出:

复制代码
hihi

15

32
相关推荐
盲盒Q17 天前
《内存之茧》
数据结构·人工智能·ruby
ZAEQgyKFs20 天前
COMSOL 模拟热流固耦合作用下二氧化碳驱替甲烷,研究驱替过程中煤层的变形,和孔渗变化,以及...
ruby
玉梅小洋1 个月前
Unity 2D游戏开发 Ruby‘s Adventure 2:主角和第一脚本
游戏·unity·游戏引擎·游戏程序·ruby·游戏开发
玉梅小洋1 个月前
Unity 2D游戏开发 Ruby‘s Adventure 1:课程介绍和资源导入
游戏·unity·游戏引擎·游戏程序·ruby
x-cmd1 个月前
[x-cmd] 告别实验阶段?Ruby 4.0 里程碑发布:Ractor 趋于稳定,性能再攀高峰
服务器·开发语言·ruby·x-cmd·ractor
龙仔7251 个月前
鲲鹏ARM系统yum安装rabbitmq并附修改端口及配置,最后一键查看
分布式·rabbitmq·ruby
KYGALYX1 个月前
服务异步通信
开发语言·后端·微服务·ruby
为什么不问问神奇的海螺呢丶1 个月前
n9e categraf rabbitmq监控配置
分布式·rabbitmq·ruby
咩图1 个月前
Sketchup软件二次开发+Ruby+VisualStudioCode
java·前端·ruby
开开心心就好1 个月前
开源免费高速看图工具,支持漫画大图秒开
linux·运维·服务器·安全·ruby·symfony·1024程序员节