Created
September 13, 2015 17:17
-
-
Save toandv/282785ea4566200fa892 to your computer and use it in GitHub Desktop.
ruby map and reduce
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
a = [1, 2, 3, 4] | |
puts a.inject(:+) | |
puts a.inject{|sum, x| sum + x} | |
b = ["1", "2"] | |
c = b.map { |e| e.to_i } | |
puts c | |
puts a.reduce(:+) | |
puts a.reduce{|sum, x| sum + x} | |
class Pair | |
attr_reader :v1, :v2 | |
def initialize(v1, v2) | |
@v1 = v1 | |
@v2 = v2 | |
end | |
end | |
books = [] | |
books << Pair.new(1, 2) | |
books << Pair.new(2, 3) | |
puts books.map{ |e| e.v1}.reduce(:+) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment