一。把一字符串,根据其中的特殊字符 “.“ 分割成数组并去除空的字符串 ,我们得到一个数组 arr
- arr = '.666.555.444.333.22.11.'.split('.').reject(&:blank?)
= 。each 的使用
数字:
- 2.0.0p0 :183 > a = [1, 2, 3, 4, 5]
- => [1, 2, 3, 4, 5]
- 2.0.0p0 :184 > a.each {|number| puts number*2}
- 2
- 4
- 6
- 8
- 10
- => [1, 2, 3, 4, 5]
- 2.0.0p0 :185 >
- 字符:
- 2.0.0p0 :191 > lower_case = ["hi", "these", "are", "some", "words"]
- => ["hi", "these", "are", "some", "words"]
- 2.0.0p0 :192 > upper_case = []
- => []
- 2.0.0p0 :193 > lower_case.each do |word|
- 2.0.0p0 :194 > upper_case << word.upcase
- 2.0.0p0 :195?> end
- => ["hi", "these", "are", "some", "words"]
- 2.0.0p0 :196 > puts upper_case
- HI
- THESE
- ARE
- SOME
- WORDS
- => nil
- 2.0.0p0 :197 >
三。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 >
把array转换成hash表。有也第一个例子的基础,这个例子应该很容易看得懂。
[1, 2, 3, 4].inject(0) { |result, element| result + element } # => 10
inject带有一个参数和block。block中的两个参数是有含义的。第一个参数reslut在inject第一次执行block时把inject带的参数付值给它,element就是数组中的元素,该例中inject一共执行4次block,每次执行block完后,最后语句的结果再付值给result,如此循环,直到遍历数组中所有元素。我们深入这个例子看每一步执行的结果。
因为数组有4个元素,所以要执行4次block操作:
第一次操作:result=0,既等于inject带的参数;element=1,既第一个元素;执行block后result + element =1,再把这个结果付值给result,所以在执行完第一次block后,result = 1。
第二次操作:result=1,既上次运行block后的最后一条语句的结果;element=2,既第二个元素;执行block后付值result=3。
如此类推,直到最后一次执行完block,生产的值为10。就是inject的返回值了。
八。shuffle[n..m]
('a'..'z').to_a.shuffle[0..7].join
一个相关的网站:http://blog.jayfields.com/2008/03/ruby-inject.html
九. flatten
- 2.0.0p247 :002 > [1,2,3,4,5,[6,7,8],[9,1,[1,2]]].flatten
- => [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 1, 2]
- 2.0.0p247 :003 >