Skip to content

Instantly share code, notes, and snippets.

@zerothabhishek
Last active August 29, 2015 14:17
Show Gist options
  • Save zerothabhishek/bba03d4a28977d17284d to your computer and use it in GitHub Desktop.
Save zerothabhishek/bba03d4a28977d17284d to your computer and use it in GitHub Desktop.
ruby-case-when-with-lambda
def foo(x)
case x
when 10 then 'The number Ten'
when String then 'A String'
when lambda{|x| x%2==1 } then 'An odd number'
when (1..9) then 'In range'
end
end
## real-life, elegent, example:
SUCCESS = ->(response) { response.code == 200 }
NOT_MODIFIED =->(response) { response.message == 'Not Modified' }
case response
when SUCCESS then 'we are good to go'
when NOT_MODIFIED then 'not a 200, but its okay anyway'
else 'uh oh, we got a problem..'
end
# source: https://coderwall.com/p/sgxmnw/lambdas-in-ruby-case-switch
## Other random examples
## Module/Class
2 === 3 #=> false
{a: 2} === {a:3} #=> true
Hash === {a:2} #=> true
{a: 2} === Hash #=> false
1.class #=> Fixnum
Fixnum === 1 #=> true
1 === Fixnum #=> false
## Proc
x = lambda{|x| x%2==1 }
x === 10 #=> false
x === 11 #=> true
11 ==== x #=> false
## Range
(1..5) === 3 #=> true
(1..5) === 13 #=> false
3 === (1..5) #=> false
## Regex
/ell/ === 'Hello' # => true
/ell/ === 'Foobar' # => false
##
"If I have a drawer labeled a, does it make sense to put b in it?"
# http://stackoverflow.com/questions/3422223/vs-in-ruby#3422349
##
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment