ruby方法定义中各类符号

  1. &:定义命名block 通常咱们定义一个带block的方法,是这样:
def test
    yield
end
test{ puts "Hello world"}

可是也能够给其一个名字,我还没搞清楚这样作的意义数组

def test(&block)
    block.call
end
test { puts "Hello World!"}
  1. *: 定义可变参数-array
def test(a, b, *c) 
    c 
end 
test(1, 2, 4, 5) #=> [4, 5]
  1. **:定义可变参数-hash
def test(a, b, **c)
    c
end
test(1, 2, str: 'hello') #=> {str: 'hello'}
test(1, 2, str: 'hello', name: 'wumz') #=> {str: 'hello', name: 'wumz'}

在ruby方法调用中,*能够把数组转化为参数,&能够把Proc或lambda转化为块ruby

相关文章
相关标签/搜索