Is the ruby operator ||= intelligent?

前端 未结 5 1993
长发绾君心
长发绾君心 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:40

    Here's another demonstration that's a bit different than the other answers in that it explicitly shows when the Hash is being written to:

    class MyHash < Hash
      def []=(key, value)
        puts "Setting #{key} = #{value}"
        super(key, value)
      end
    end
    
    >> h = MyHash.new
    => {}
    >> h[:foo] = :bar
    Setting foo = bar
    => :bar
    >> h[:bar] ||= :baz
    Setting bar = baz
    => :baz
    >> h[:bar] ||= :quux
    => :baz
    

    And by way of comparison:

    // continued from above
    >> h[:bar] = h[:bar] || :quuux
    Setting bar = baz
    => :baz
    

提交回复
热议问题