- 在调用代码块的时候,想要传入参数,普通参数需要写在&block参数前
一个关于代码块基础的小实验:
class A
def a(v1, v2, v3)
puts 'hello!'
end
def b(&block)
block.call
end
def c(trail, &block)
if trail.present?
puts "ok"
else
if block_given?
block.call
end
end
end
def d(_v, &block)
if _v.present?
puts "ok"
else
if block_given?
block.call('block')
else
puts 'no block'
end
end
end
end
# aa=A.new
# aa.c('trail') {puts 'nice'} => ok
# aa.c('') {puts 'nice'} => nice
# aa.c('') => nil
# aa.c(true) {} => ok
# aa.c(true) {puts 'axu'} => ok
# aa.c('') {puts 'axu'} => axu
#
# aa.d('a') {|i| puts i} => ok
# aa.d('') {|i| puts i} => block
# aa.d('') => no block
2017-09-26