Last active
August 29, 2015 14:17
-
-
Save sivabudh/2ac13e6be0b8afb385ac to your computer and use it in GitHub Desktop.
What's the difference between functional and imperative? Find out
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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