Install ruby
$ irb
.map()
Invokes the given {block} once for each element of self, creating a new array with the values returned by the block.
Documentation here.
1.9.3-p448 :007 > patients = ['Prayag', 'Paras', 'James', 'Angelina', 'Scarlette', 'Christian']
=> ["Prayag", "Paras", "James", "Angelina", "Scarlette", "Christian"]
1.9.3-p448 :008 > patients.map {|patient| patient.upcase}
=> ["PRAYAG", "PARAS", "JAMES", "ANGELINA", "SCARLETTE", "CHRISTIAN"]
1.9.3-p448 :010 > patients.map {|patient| patient.reverse}
=> ["gayarP", "saraP", "semaJ", "anilegnA", "ettelracS", "naitsirhC"]
1.9.3-p448 :011 > patients.map {|patient| patient.size}
=> [6, 5, 5, 8, 9, 9]
.reduce()
Combines all elements of enum by applying a binary operation specified by a {block}.
Documentation here.
1.9.3-p448 :012 > rainbow.reduce(0) {|acc, n| acc += 1}
=> 30
1.9.3-p448 :014 > patients.reduce(0) {|acc, n| acc += n.length}
=> 42
1.9.3-p448 :016 > patients.reduce([]) {|acc, n| acc.push(n.upcase)}
=> ["PRAYAG", "PARAS", "JAMES", "ANGELINA", "SCARLETTE", "CHRISTIAN"]
References
Understanding Ruby’s Select, Map, and Reduce, http://feynmanliang.com/?p=319
Understanding map and reduce, http://railspikes.com/2008/8/11/understanding-map-and-reduce
$ irb
.map()
Invokes the given {block} once for each element of self, creating a new array with the values returned by the block.
Documentation here.
1.9.3-p448 :007 > patients = ['Prayag', 'Paras', 'James', 'Angelina', 'Scarlette', 'Christian']
=> ["Prayag", "Paras", "James", "Angelina", "Scarlette", "Christian"]
1.9.3-p448 :008 > patients.map {|patient| patient.upcase}
=> ["PRAYAG", "PARAS", "JAMES", "ANGELINA", "SCARLETTE", "CHRISTIAN"]
1.9.3-p448 :010 > patients.map {|patient| patient.reverse}
=> ["gayarP", "saraP", "semaJ", "anilegnA", "ettelracS", "naitsirhC"]
1.9.3-p448 :011 > patients.map {|patient| patient.size}
=> [6, 5, 5, 8, 9, 9]
.reduce()
Combines all elements of enum by applying a binary operation specified by a {block}.
Documentation here.
=> 30
1.9.3-p448 :014 > patients.reduce(0) {|acc, n| acc += n.length}
=> 42
1.9.3-p448 :016 > patients.reduce([]) {|acc, n| acc.push(n.upcase)}
=> ["PRAYAG", "PARAS", "JAMES", "ANGELINA", "SCARLETTE", "CHRISTIAN"]
References
Understanding Ruby’s Select, Map, and Reduce, http://feynmanliang.com/?p=319
Understanding map and reduce, http://railspikes.com/2008/8/11/understanding-map-and-reduce
No comments:
Post a Comment