Ruby case when

@h6165

Abhishek Yadav

ரூபீ ப்ரோக்ராமர்

Co-organizer: Chennai.rb

Case when

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

Case when


## 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

Case when

## 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

Case when

## Proc
x = lambda{|x| x%2==1 }
x === 10                 #=> false
x === 11                 #=> true
11 ==== x                #=> false

Case when

## Range
(1..5) === 3           #=> true
(1..5) === 13          #=> false
3 === (1..5)           #=> false

Case when


## Regex
/ell/ === 'Hello'     # => true
/ell/ === 'Foobar'    # => false

Case when

## 
"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
##

ruby case when

By Abhishek Yadav

ruby case when

  • 1,001