Last active
August 29, 2015 14:17
-
-
Save sivabudh/9ea8d5da71cdd36b412a to your computer and use it in GitHub Desktop.
Imperative vs Functional
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 (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