Skip to content

Instantly share code, notes, and snippets.

@drKreso
Forked from avdi/when.rb
Created December 6, 2011 07:05
Show Gist options
  • Select an option

  • Save drKreso/1437135 to your computer and use it in GitHub Desktop.

Select an option

Save drKreso/1437135 to your computer and use it in GitHub Desktop.
Experimenting with Object#when in Ruby
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
@avdi
Copy link

avdi commented Dec 6, 2011

I'm not sure I understand the question - can you restate it?

@drKreso
Copy link
Author

drKreso commented Dec 6, 2011

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.

@drKreso
Copy link
Author

drKreso commented Dec 6, 2011

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

@avdi
Copy link

avdi commented Dec 6, 2011

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?

@drKreso
Copy link
Author

drKreso commented Dec 6, 2011

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?

@avdi
Copy link

avdi commented Dec 6, 2011 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment