**map,collect,inject,reject,select的应用**
==============================================
三。collect的使用
2.0.0p0 :197 > lower_case = ["hi", "these", "are", "some", "words"]
=> ["hi", "these", "are", "some", "words"]
2.0.0p0 :198 > upper_case = lower_case.collect { |word| word.upcase }
=> ["HI", "THESE", "ARE", "SOME", "WORDS"]
2.0.0p0 :199 > puts upper_case.inspect
["HI", "THESE", "ARE", "SOME", "WORDS"]
=> nil
2.0.0p0 :200 >
四。map的使用
2.0.0p0 :200 > a = [ "a", "b", "c", "d" ]
=> ["a", "b", "c", "d"]
2.0.0p0 :201 > a.map { |x| x + "!" }
=> ["a!", "b!", "c!", "d!"]
2.0.0p0 :202 > a
=> ["a", "b", "c", "d"]
2.0.0p0 :203 >
五。reject的使用
2.0.0p0 :210 > (1..30).reject { |n| n % 2 == 0 }
=> [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29]
2.0.0p0 :217 > a = [1,2,3,4]
=> [1, 2, 3, 4]
2.0.0p0 :218 > a.reject {|n| n > 2}
=> [1, 2]
2.0.0p0 :219 >
六.select的使用
2.0.0p0 :224 > a = [1,2,3,4]
=> [1, 2, 3, 4]
2.0.0p0 :225 > a.select {|n| n > 2}
=> [3, 4]
2.0.0p0 :226 >
七.inject的使用
enum.inject(init_value) {|memo,obj| block}
enum.inject{ |memo,obj| block }
2.0.0p0 :226 > [1, 2, 3, 4].inject { |result, element| result + element }
=> 10
2.0.0p0 :227 > hash = [[:first_name, 'Shane'], [:last_name, 'Harvie']].inject({}) do |result, element|
2.0.0p0 :228 > result[element.first] = element.last
2.0.0p0 :229?> result
2.0.0p0 :230?> end
=> {:first_name=>"Shane", :last_name=>"Harvie"}
2.0.0p0 :231 >