首页 > 代码库 > ruby arr常用的方法

ruby arr常用的方法

soyo@soyo-ThinkPad-X1:~$ irb
2.4.1 :001 > arr =[1,-1,2,3,-4]
 => [1, -1, 2, 3, -4] 
2.4.1 :002 > arr.each{|e|p e}
1
-1
2
3
-4
 => [1, -1, 2, 3, -4] 
2.4.1 :003 > arr.reverse_each {|e| p e}
-4
3
2
-1
1
 => [1, -1, 2, 3, -4] 
2.4.1 :004 > arr.each_with_index{ |e,i| p [e,i]}
[1, 0]
[-1, 1]
[2, 2]
[3, 3]
[-4, 4]
 => [1, -1, 2, 3, -4] 
2.4.1 :005 > arr.sort
 => [-4, -1, 1, 2, 3] 
2.4.1 :006 > arr
 => [1, -1, 2, 3, -4] 
2.4.1 :007 > arr.sort!
 => [-4, -1, 1, 2, 3] 
2.4.1 :008 > arr
 => [-4, -1, 1, 2, 3] 
2.4.1 :009 > arr.select{|e|e>0}
 => [1, 2, 3] 
2.4.1 :010 > arr<< nil
 => [-4, -1, 1, 2, 3, nil] 
2.4.1 :011 > arr.compact
 => [-4, -1, 1, 2, 3] 
2.4.1 :012 > arr
 => [-4, -1, 1, 2, 3, nil] 
2.4.1 :013 > arr.compact!
 => [-4, -1, 1, 2, 3] 
2.4.1 :014 > arr
 => [-4, -1, 1, 2, 3] 
2.4.1 :015 > arr.compact!
 => nil 
2.4.1 :016 > arr
 => [-4, -1, 1, 2, 3] 
2.4.1 :017 > arr.any?{|e|e<)}
SyntaxError: (irb):17: syntax error, unexpected ‘)‘
arr.any?{|e|e<)}
               ^
	from /home/soyo/.rvm/rubies/ruby-2.4.1/bin/irb:11:in `<main>‘
2.4.1 :018 > arr.any?{|e|e<0}
 => true 
2.4.1 :019 > arr.any?{|e| e>0}
 => true 
2.4.1 :020 > arr.any?{|e| e>8}
 => false 
2.4.1 :021 >  

  

ruby arr常用的方法