How can I memoize a method that may return true, false, or nil in Ruby?

前端 未结 2 945
醉酒成梦
醉酒成梦 2020-12-16 13:49

Obviously ||= won\'t work

def x?
  @x_query ||= expensive_way_to_calculate_x
end

because if it turns out to be false

2条回答
  •  春和景丽
    2020-12-16 14:16

    To account for nil, use defined? to see if the variable has been defined:

    def x?
      return @x_query if defined? @x_query
      @x_query = expensive_way_to_calculate_x
    end
    

    defined? will return nil if the variable hasn't been defined, or the string "instance_variable" otherwise:

    irb(main):001:0> defined? @x
    => nil
    irb(main):002:0> @x = 3
    => 3
    irb(main):003:0> defined? @x
    => "instance-variable"
    

提交回复
热议问题