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

相關文章
相關標籤/搜索