Last active
April 26, 2017 19:00
-
-
Save rwz/c166ebaaacd78a92125fc2c490c9552a to your computer and use it in GitHub Desktop.
dynamic method definition in ruby
This file contains hidden or 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 MyClass | |
def static_yield(*) | |
yield if block_given? | |
end | |
define_method :dynamic_yield do |*| | |
yield if block_given? | |
end | |
define_method :dynamic_yield_fix do |*, &block| | |
block&.call | |
end | |
end | |
MyClass.new.static_yield { puts "Now you see me!" } # => Now you see me! | |
MyClass.new.dynamic_yield { puts "Now you don't!" } # => nil ಠ_ಠ | |
MyClass.new.dynamic_yield_fix { puts "This works though." } # => This works though. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment