rubyjs / therubyrhino

Embed the Mozilla Rhino Javascript interpreter into Ruby
155 stars 40 forks source link

simplify memoization logic #20

Closed cowboyd closed 12 years ago

cowboyd commented 12 years ago

replace some if defined? statements with a memoized if-statement.

kares commented 12 years ago

thanks for the pull, I feel your "ugly ruby" pain but there's a reason for using defined? due possible nils whatever the method outcome is the defined? statements makes sure it only executes the code once ...

try this :

class Test

  def hello(msg = 'world')
    @hello ||= begin
      puts "hello #{msg}"
      msg
    end
  end

  def holla(msg = 'amigo')
    return @holla if defined? @holla
    @holla ||= begin
      puts "holla #{msg}"
      msg
    end
  end

end

test = Test.new
3.times { test.hello(nil) } # prints hello 3 times
3.times { test.holla(nil) } # prints holla once ...
cowboyd commented 12 years ago

Ah, I see, fair enough.