Skip to content

Instantly share code, notes, and snippets.

@revans
Last active August 8, 2018 12:34
Show Gist options
  • Save revans/6a4d4baa0a3fb537774fe0fb19a24c03 to your computer and use it in GitHub Desktop.
Save revans/6a4d4baa0a3fb537774fe0fb19a24c03 to your computer and use it in GitHub Desktop.
Using attr_reader with ||= and getting interesting results
# ruby 2.5.0p0 (2017-12-25 revision 61468)
class Demo
attr_reader :first_name
def initialize(first_name)
@first_name = first_name
end
def hi(myname = nil)
puts "Hello, #{first_name}"
first_name ||= myname
puts "Hello, #{first_name}"
end
def test(myname = nil)
puts "Hello, #{first_name}"
first_name = first_name || myname
puts "Hello, #{first_name}"
end
def hello(myname = nil)
puts "Hello, #{first_name}"
first_name = first_name ? first_name : myname
puts "Hello, #{first_name}"
end
end
# demo = Demo.new('John')
# demo.first_name #=> 'John'
# demo.hi('Bill')
#=> Hello, John
#=> Hello, Bill
# demo.test('Bill')
#=> Hello, John
#=> Hello, Bill
# demo.hello('Bill')
#=> Hello, John
#=> Hello, Bill
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment