Skip to content

Instantly share code, notes, and snippets.

@tpett
Created May 9, 2020 16:52
Show Gist options
  • Save tpett/61cec25a31e9d711466d67b7cc1a9b29 to your computer and use it in GitHub Desktop.
Save tpett/61cec25a31e9d711466d67b7cc1a9b29 to your computer and use it in GitHub Desktop.
Contrived example to show a use of Proc
# frozen_string_literal: true
def useless_number_classify(number)
if number == 5
[:five, number]
elsif number.odd?
[:odd, number]
elsif number.even?
[:even, number]
end
end
p useless_number_classify(5)
p useless_number_classify(4)
p useless_number_classify(111)
def useless_number_classify_with_proc(number)
check_five = proc do |n|
return [:five, n] if n == 5
end
check_odd = proc do |n|
return [:odd, n] if n.odd?
end
check_even = proc do |n|
return [:even, n] if n.even?
end
check_five.(number)
check_odd.(number)
check_even.(number)
end
p useless_number_classify_with_proc(5)
p useless_number_classify_with_proc(4)
p useless_number_classify_with_proc(111)
@tpett
Copy link
Author

tpett commented May 9, 2020

An example of how Proc can be used to intentionally cause an early return on a method. A lambda in this case would only return a value for even numbers as it is the last line of the method. A proc will cause an early return of the method so any subsequent calls would not be executed.

Obviously, the first implementation is better. The procs do not make this more readable or faster, but there are situations where it could potentially add some flexibility that you might want when doing some metaprogramming task.

@clintmiller
Copy link

We’re definitely in the darker corners of Ruby at this point!

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