Skip to content

Instantly share code, notes, and snippets.

@mwlang
Created April 10, 2015 15:30
Show Gist options
  • Save mwlang/53c2dbe86857a958caf5 to your computer and use it in GitHub Desktop.
Save mwlang/53c2dbe86857a958caf5 to your computer and use it in GitHub Desktop.
How to pass options such that we can both lazily evaluate and reference variables within the class?
>> ruby foo.rb
lazy?
gonna say hello
Hello
lazy?
hello: undefined local variable or method `hello' for main:Object
class Foo
def hello
puts "gonna say hello"
"Hello"
end
attr_reader :say_it
def initialize options = {}
@say_it = options[:another_way] || method(:hello)
end
def speak
puts say_it.call
end
end
begin
foobar = Foo.new
puts "lazy?"
puts foobar.speak
rescue Exception => e
puts "#{e.name}: #{e.message}"
end
begin
foobaz = Foo.new(another_way: lambda { "#{hello}, Sir!" })
puts "lazy?"
puts foobaz.speak
rescue Exception => e
puts "#{e.name}: #{e.message}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment