Created
May 29, 2011 15:43
-
-
Save zerowidth/997875 to your computer and use it in GitHub Desktop.
a demonstration of the ||= idiom
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby -wKU | |
# | |
# a demonstration of the ||= idiom | |
# | |
# x ||= y | |
# | |
# is usually translated as | |
# | |
# x = x || y | |
# | |
# but as demonstrated here, is better translated as | |
# | |
# x || x = y | |
# | |
class A | |
def initialize | |
@x = nil | |
end | |
def x | |
puts " returning x: #{@x.inspect}" | |
@x | |
end | |
def x=(value) | |
puts " setting x to #{value.inspect}" | |
@x = value | |
end | |
end | |
y = "y" | |
puts "\n----- retrieval -----" | |
a = A.new | |
a.x | |
puts "\n----- assignment -----" | |
a = A.new | |
a.x = "foo" | |
puts "\n----- a.x = a.x || y -----" | |
a = A.new | |
a.x = a.x || y | |
puts "and again:" | |
a.x = a.x || y | |
puts "\n----- a.x || a.x = y -----" | |
a = A.new | |
a.x || a.x = y | |
puts "and again:" | |
a.x || a.x = y | |
puts "\n----- a.x ||= y -----" | |
a = A.new | |
a.x ||= y | |
puts "and again:" | |
a.x ||= y | |
puts <<-summary | |
----- and thus ----- | |
x ||= y | |
only assigns y if x isn't already set, i.e. | |
x || x = y | |
and not | |
x = x || y | |
summary | |
# see also: http://www.ruby-forum.com/topic/151660/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment