puts 5 + 6 # => 11
a = 5 b = 6 puts a + b # => 11
addition = lambda { |a, b| return a+b }
puts addition.call(5, 6)
# => 11
[1, 2, 3].each do |i| puts i end #=> 1 2 3
def test;end
test{ puts i}
def test
yield
end
test{puts "hello test!"}
def test(x)
yield(x)
end
test('world!'){|x| puts "hello #{x}"}
def test(&block)
block.call("world")
end
test{|msg| puts "hello #{msg}"}
block到了方法内部,已经被&转化为了一个Proc对象。
def test(&block)
inner_test(&block)
end
def inner_test
yield("haha!")
end
test{|msg| puts "hello #{msg}"}
empty_block = lambda { }
puts empty_block.object_id
# => 28765760
puts empty_block.class
# => Proc
puts empty_block.class.superclass
# => Object
class Calculator def add(a, b) return a+b end end puts Calculator.new.add(5, 6) # => 11
class Calculator
def add(a, b)
return a+b
end
end
addition_method = Calculator.new.method("add")
addition = addition_method.to_proc
puts addition.call(5, 6)
# => 11
Addition = lambda { |a, b| return a+b }
Subtraction = lambda { |a, b| return a-b }
Multiplication = lambda { |a, b| return a*b }
Division = lambda { |a, b| return a/b }
# 使用的时候通过call来使用
Addition.call(5, 6)
# => 11
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有