-
-
Save drKreso/1437135 to your computer and use it in GitHub Desktop.
Experimenting with Object#when 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 Object | |
| def when(matcher) | |
| if matcher === self then yield(self) else self end | |
| end | |
| end | |
| # I read it like this : if "when" lambda/proc is true execute block, otherwise return self | |
| #deeply confused | |
| #Proc#=== is equivalent to Proc#call | |
| #kinda like this? | |
| matcher.call(self) | |
| #BUT this is of course not working for nil - why is it working for | |
| matcher === self | |
| #I don't know what am I missing | |
Author
When the matcher is nil Ruby calls NilClass#=== which is the same as Object#===. Object#=== simply delegates to Object#==.
You could use any object which responds to ===:
obj.when(/foo/) { ... }
obj.when(Integer) { ... }
obj.when(1...9) { ... }
Etc.
Does that clear it up?
Author
It sure does. My mind is a bit blown right now, so I might need some time to digest all this. Would you mind if I blogged a bit about this?
On Tue, Dec 6, 2011 at 1:59 PM, Kresimir Bojcic ***@***.*** wrote:
It sure does. My mind is a bit blown right now, so I might need some time to digest all this. Would you mind if I blogged a bit about this?
Go for it!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think this would be equivalent:
def when(matcher)
if (matcher.nil? || matcher.call(self)) then yield(self) else self end
end
If matcher is nil or matcher when called produces true then call block and pass self as arumnet, otherwise pass self along.
This would be a bit more explicit
def when(matcher, &block)
if (matcher.nil? || matcher.call(self)) then block.call(self) else self end
end