Skip to content

Instantly share code, notes, and snippets.

@toandv
Created September 13, 2015 17:17
Show Gist options
  • Save toandv/282785ea4566200fa892 to your computer and use it in GitHub Desktop.
Save toandv/282785ea4566200fa892 to your computer and use it in GitHub Desktop.
ruby map and reduce
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