-
-
Save drKreso/1437135 to your computer and use it in GitHub Desktop.
| 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 | |
matcher === self
Here you call matcher lambda with self as a param right?
Doc says is it same as Proc.call. Is it possible to write aboove statement with call? If not why not what is the difference...
proc === obj → result_of_proc click to toggle source
Invokes the block with obj as the proc’s parameter like Proc#call. It is to allow a proc object to be a target of when clause in a case statement.
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
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?
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?
I'm not sure I understand the question - can you restate it?