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/2ac13e6be0b8afb385ac to your computer and use it in GitHub Desktop.
Save sivabudh/2ac13e6be0b8afb385ac to your computer and use it in GitHub Desktop.
What's the difference between functional and imperative? Find out
puts "Hello. Welcome to the Functional World!"
#
# This is how to do it imperative style (aka: Stupid Java programmer)
#
array = [1,2,3,4]
new_array = []
array.each do |n|
if n % 2 == 0
new_array.push n
end
end
#
# Alterative syntax that a mint Java-programmer-turned-Ruby-programmer probably would do
#
array = [1,2,3,4]
new_array = []
array.each do |n|
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.select do |n|
if n.even?
true
else
false
end
end
#
# The truly functional way (smart Rubyist. Aka Functional Nirvana). Notice the
# output variable's name has been smartly renamed
#
even_numbers = [1,2,3,4].select { |n| n.even? }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment