2022-06-10|閱讀時間 ‧ 約 1 分鐘

&: and &. in Ruby

    直接來看範例吧

    &:

    &:將一組陣列中的元素轉換成字串
    cats = [1, 2, 3, 4]
    當使用:
    cats.map do |x| x.to_s end
    cats.map {|x| x.to_s }
    會得到:
    ["1", "2", "3", "4"]

    其中的block以及block變數可以用&:代替,然後:後面接續方法:
    cats.map(&:to_s)

    &.

    範例1
    a = []
    x = a.nil?
    puts x => true;

    a = []
    x = a&.nil?
    puts x => 不會執行puts

    加入&.會判斷receiver如果是nil,就不會執行puts。

    範例2
    @candidate&.create
    如果 @candidate為nil,就不會執行create方法,如此便不會出現undefined method `[]' for nil:NilClass的錯誤訊息。
    分享至
    成為作者繼續創作的動力吧!
    紀錄並分享學習 Code 的過程~
    從 Google News 追蹤更多 vocus 的最新精選內容從 Google News 追蹤更多 vocus 的最新精選內容

    發表回應

    成為會員 後即可發表留言