Common Ruby Idioms

前端 未结 15 2050
星月不相逢
星月不相逢 2020-12-07 07:13

One thing I love about ruby is that mostly it is a very readable language (which is great for self-documenting code)

However, inspired by this question: Ruby Code ex

15条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-07 07:32

    By the way, from the referenced question

    a ||= b 
    

    is equivalent to

    if a == nil   
      a = b 
    end
    

    That's subtly incorrect, and is a source of bugs in newcomers' Ruby applications.

    Since both (and only) nil and false evaluate to a boolean false, a ||= b is actually (almost*) equivalent to:

    if a == nil || a == false
      a = b
    end
    

    Or, to rewrite it with another Ruby idiom:

    a = b unless a
    

    (*Since every statement has a value, these are not technically equivalent to a ||= b. But if you're not relying on the value of the statement, you won't see a difference.)

提交回复
热议问题