Is the ruby operator ||= intelligent?

前端 未结 5 1992
长发绾君心
长发绾君心 2020-11-29 10:30

I have a question regarding the ||= statement in ruby and this is of particular interest to me as I\'m using it to write to memcache. What I\'m wondering is, does ||= check

5条回答
  •  [愿得一人]
    2020-11-29 10:36

    CACHE[:some_key] ||= "Some String"
    

    is equivalent to

    CACHE[:some_key] = "Some String" unless CACHE[:some_key]
    

    (which is equivalent to if + nil? unless CACHE[:some_key] is a boolean value).

    In other words: yes, ||= will only write if the LHS is nil or false.

提交回复
热议问题