Skip to content

Instantly share code, notes, and snippets.

@vargonaut
Created June 29, 2016 18:35
Show Gist options
  • Select an option

  • Save vargonaut/e7233315a961146655026b6129ca3c16 to your computer and use it in GitHub Desktop.

Select an option

Save vargonaut/e7233315a961146655026b6129ca3c16 to your computer and use it in GitHub Desktop.
Show how proc aliases === to call
# On procs, Ruby aliases `===` to `call`
# The comparator that a case statement uses is `===`
# This means that you can use procs as when clauses
a_proc = proc { "I'm a proc" }
b_proc = proc {|x| "I'm a proc that says '#{x}'"}
a_proc.call # => I'm a proc
b_proc.call # => I'm a proc that says ''
b_proc.call "Hello!" #=> I'm a proc that says 'Hello!'
a_proc.=== #=> I'm a proc
b_proc.=== #=> I'm a proc that says ''
b_proc.=== "So long!" #=> I'm a proc that says 'So long!'
c_proc = proc {|x| x && x }
c_proc.call(true) #=> true
c_proc.call(false) #=> false
c_proc.===(true) #=> true
c_proc.===(false) #=> false
@multi_of_5 = proc {|x| x % 5 == 0 }
@multi_of_3 = proc {|x| x % 3 == 0 }
def check_multi(n)
case n
when @multi_of_5
"Its definitely a multiple of 5"
when @multi_of_3
"Its definitely a multiple of 3"
else
"No clue what's up with #{n}"
end
end
check_multi(4) #=> No clue what's up with 4
check_multi(6) #=> Its definitely a multiple of 3
check_multi(10) #=> Its definitely a multiple of 5
IS_US ->{|x| x.downcase.in?('us', 'usa')}
case country
when IS_US
do_thing_with_us
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment