Last active
August 29, 2015 14:05
-
-
Save coalwater/4082e2609d3c03370e82 to your computer and use it in GitHub Desktop.
Select, Reject, Collect, Detect, Inject
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
y = [1,2,3,4].collect {|number| number ** 2 } | |
# y will equal [1, 4, 9, 16] |
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
y = [1,2,3,4].detect {|number| number%2 == 0} | |
# y will equal 2 | |
y = [4,3,2,1].detect {|number| number%2 == 0} | |
# y will equal 4 |
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
y = [1,2,3,4].inject(0) {|accumulator, number| accumulator += number} | |
# y will equal 10 ( 1+2+3+4 ) | |
y = [1,2,3,4].inject(10) {|accumulator, number| accumulator += number } | |
# y will equal 20, ( 10 as the accumulator initial value + 1+2+3+4 ) | |
y = [1,2,3,4].inject([]) {|accumulator, number| accumulator << number*2 } | |
# y will equal [2,4,6,8] |
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
y = [1,2,3,4].reject{|number| number % 2 == 0} | |
# y will equal [1,3] |
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
y = [1,2,3,4].select {|number| number % 2 == 0} | |
# y will equal [2,4] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment