Skip to content

Instantly share code, notes, and snippets.

@zerowidth
Created May 29, 2011 15:43
Show Gist options
  • Save zerowidth/997875 to your computer and use it in GitHub Desktop.
Save zerowidth/997875 to your computer and use it in GitHub Desktop.
a demonstration of the ||= idiom
#!/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