Skip to content

Instantly share code, notes, and snippets.

@sivabudh
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sivabudh/9ea8d5da71cdd36b412a to your computer and use it in GitHub Desktop.
Save sivabudh/9ea8d5da71cdd36b412a to your computer and use it in GitHub Desktop.
Imperative vs Functional
puts "Hello. Welcome to the Functional World!"
# This is how to do it imperative style (Stupid Java programmer)
array = [1,2,3,4]
new_array = []
array.each do |n|
if n % 2 == 0
new_array.push n
end
# alternate syntax
new_array.push n if n % 2 == 0
end
# This is another way to do it imperative style (smarter Ruby programmer)
array = [1,2,3,4]
new_array = array.map do |n|
if n.even?
n
else
next
end
end
# The truly functional way (smart Rubyist)
even_numbers = [1,2,3,4].select { |n| n.even? }
puts even_numbers
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment