Created
April 10, 2015 15:30
-
-
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?
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
>> ruby foo.rb | |
lazy? | |
gonna say hello | |
Hello | |
lazy? | |
hello: undefined local variable or method `hello' for main:Object |
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
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