美文网首页Ruby
Ruby关于数组的的一些实用方法

Ruby关于数组的的一些实用方法

作者: zhaoyshine | 来源:发表于2017-08-16 15:48 被阅读66次

一、Array的用法
1.新建数组

ary = [1, "two", 3.0] #=> [1, "two", 3.0]
ary = Array.new#=> []
Array.new(3) #=> [nil, nil, nil]
Array.new(3, true) #=> [true, true, true]
Array.new(4) { Hash.new } #=> [{}, {}, {}, {}]
empty_table = Array.new(3) { Array.new(3) } #=> [[nil, nil, nil], [nil, nil, nil], [nil, nil, nil]]
Array({:a => "a", :b => "b"}) #=> [[:a, "a"], [:b, "b"]]

2.元素访问

arr = [1, 2, 3, 4, 5, 6]  arr[2] #=> 3
arr[100] #=> nil 
arr[-3] #=> 4 
arr[2, 3] #=> [3, 4, 5] 
arr[1..4] #=> [2, 3, 4, 5]
arr.at(0) #=> 1
arr = ['a', 'b', 'c', 'd', 'e', 'f']
arr.fetch(100) #=> IndexError: index 100 outside of array bounds: -6...6 
arr.fetch(100, "oops") #=> "oops" 
arr.first #=> 1 
arr.last #=> 6
arr.take(3) #=> [1, 2, 3]
arr.drop(3) #=> [4, 5, 6]

3.获取数组信息

browsers = ['Chrome', 'Firefox', 'Safari', 'Opera', 'IE'] 
browsers.length #=> 5
browsers.count #=> 5
browsers.empty? #=> false
browsers.include?('Konqueror') #=> false

4.向数组添加元素

arr = [1, 2, 3, 4]
arr.push(5) #=> [1, 2, 3, 4, 5]
arr <<6 #=> [1, 2, 3, 4, 5, 6]
arr.unshift(0) #=> [0, 1, 2, 3, 4, 5, 6]
a = [ "b", "c", "d" ]  
a.unshift("a") #=> ["a", "b", "c", "d"] 
a.unshift(1, 2) #=> [ 1, 2, "a", "b", "c", "d"]
arr.insert(3, 'apple') #=> [0, 1, 2, 'apple', 3, 4, 5, 6]
arr.insert(3, 'orange', 'pear', 'grapefruit') #=> [0, 1, 2, "orange", "pear", "grapefruit", "apple", 3, 4, 5, 6]

5.从数组删除元素

arr =  [1, 2, 3, 4, 5, 6] 
arr.pop #=> 6
arr #=> [1, 2, 3, 4, 5] 
arr.pop(2) #=>[4,5]   
arr #=>[1,2,3]  
arr.shift #=> 1 
arr #=> [2, 3, 4, 5]  
arr.delete_at(2) #=> 4  
arr #=> [2, 3, 5]  
arr = [1, 2, 2, 3]  
arr.delete(2) #=> [1, 3]
a = [ "a", "b", "b", "b", "c" ] 
a.delete("b") #=> "b"  
a #=> ["a", "c"]  
a.delete("z") #=> nil  
a.delete("z") { "not found" } #=> "not found"
arr = ['foo', 0, nil, 'bar', 7, 'baz', nil] 
arr.compact #=> ['foo', 0, 'bar', 7, 'baz'] 
arr #=> ['foo', 0, nil, 'bar', 7, 'baz', nil]
arr.compact! #=> ['foo', 0, 'bar', 7, 'baz'] 
arr #=> ['foo', 0, 'bar', 7, 'baz']
arr = [2, 5, 6, 556, 6, 6, 8, 9, 0, 123, 556]
arr.uniq #=> [2, 5, 6, 556, 8, 9, 0, 123]
a = [ "a", "b", "c" ]
a.delete_if {|x| x >= "b" } #=> ["a"]
a = [ "a", "b", "c" ] 
a.slice!(1) #=> "b"
a #=> ["a", "c"]
a.slice!(-1) #=> "c"
a #=> ["a"] 
a.slice!(100) *#=> nil
a #=> ["a"]

6.遍历数组

arr = [1, 2, 3, 4, 5] 
arr.each { |a| printa -= 10, " " } # prints: -9 -8 -7 -6 -5#=> [1, 2, 3, 4, 5]
words = %w[rats live on no evil star]
str = ""words.reverse_each { |word| str += "#{word.reverse} " } str#=> "rats live on no evil star "
arr.map { |a| 2*a } #=> [2, 4, 6, 8, 10]
arr#=> [1, 2, 3, 4, 5]
arr.map! { |a| a**2 } #=> [1, 4, 9, 16, 25]
arr#=> [1, 4, 9, 16, 25]

7.从数组选择元素

arr = [1, 2, 3, 4, 5, 6]
arr.select { |a| a > 3 } #=> [4, 5, 6]
arr.reject { |a| a < 3 } #=> [3, 4, 5, 6]
arr.reject { |a| a == 3 } #=> [1, 2, 4, 5, 6]
arr.drop_while { |a| a < 4 } #=> [4, 5, 6]
arr#=> [1, 2, 3, 4, 5, 6]
arr.delete_if { |a| a < 4 } #=> [4, 5, 6]
arr#=> [4, 5, 6]
arr = [1, 2, 3, 4, 5, 6]
arr.keep_if { |a| a < 4 } #=> [1, 2, 3]
arr#=> [1, 2, 3]

8.获取两个数组相同的元素

[ 1, 1, 3, 5 ] & [ 1, 2, 3 ] #=> [ 1, 3 ]
[ 'a', 'b', 'b', 'z' ] & [ 'a', 'b', 'c' ] #=> [ 'a', 'b' ]

9.数组成倍夸张

[ 1, 2, 3 ] * 3 #=> [ 1, 2, 3, 1, 2, 3, 1, 2, 3 ]
[ 1, 2, 3 ] * "," #=> "1,2,3"  同: [ 1, 2, 3 ].join(',') 

10.数组相加

[ 1, 2, 3 ] + [ 4, 5 ] #=> [ 1, 2, 3, 4, 5 ]
a = [ "a", "b", "c" ] 
a + [ "d", "e", "f" ] 
a #=> [ "a", "b", "c", "d", "e", "f" ]

11.数组相减

[ 1, 1, 2, 2, 3, 3, 4, 5 ] - [ 1, 2, 4 ]

12.数组追加

[ 1, 2 ] << "c" << "d" << [ 3, 4 ]#=> [ 1, 2, "c", "d", [ 3, 4 ] ]
[ "a", "b" ].concat( ["c", "d"] ) #=> [ "a", "b", "c", "d" ] 
a = [ 1, 2, 3 ] 
a.concat( [ 4, 5 ] ) 
a #=> [ 1, 2, 3, 4, 5 ]

13.数组比较

[ "a", "a", "c" ] <=> [ "a", "b", "c" ]  #=> -1
[ 1, 2, 3, 4, 5, 6 ] <=> [ 1, 2 ]#=> +1
[ "a", "c" ]== [ "a", "c", 7 ] #=> false 
[ "a", "c", 7 ] == [ "a", "c", 7 ] #=> true 
[ "a", "c", 7 ] == [ "a", "d", "f" ] #=> false

14.获取数组中的元素

a = [ "a", "b", "c", "d", "e" ] 
a[2] + a[0] + a[1] #=> "cab" 
a[6] #=> nil 
a[1, 2] #=> [ "b", "c" ] 
a[1..3] #=> [ "b", "c", "d" ] 
a[4..7] #=> [ "e" ] 
a[6..10] #=> nil 
a[-3, 3] #=> [ "c", "d", "e" ] # special cases 
a[5] #=> nil 
a[6, 1] #=> nil 
a[5, 1] #=> [] 
a[5..10] #=> []

15.数组赋值

a = Array.new 
a[4] = "4"; #=> [nil, nil, nil, nil, "4"] 
a[0, 3] = [ 'a', 'b', 'c' ] #=> ["a", "b", "c", nil, "4"] 
a[1..2] = [ 1, 2 ] #=> ["a", 1, 2, nil, "4"] 
a[0, 2] = "?" #=> ["?", 2, nil, "4"] 
a[0..2] = "A" #=> ["A", "4"] 
a[-1]  = "Z" #=> ["A", "Z"] 
a[1..-1] = nil #=> ["A", nil] 
a[1..-1] = [] #=> ["A"] 
a[0, 0] = [ 1, 2 ] #=> [1, 2, "A"] 
a[3, 0] = "B" #=> [1, 2, "A", "B"]

16.计算字符串中自身缩写集

require 'abbrev' 
%w{ car cone }.abbrev #=> {"car"=>"car", "ca"=>"car", "cone"=>"cone", "con"=>"cone", "co"=>"cone"}
%w{ number cone }.abbrev#=> {"number"=>"number", "numbe"=>"number", "numb"=>"number", "num"=>"number", "nu"=>"number", "n"=>"number", "cone"=>"cone", "con"=>"cone", "co"=>"cone", "c"=>"cone"}
%w{ fast boat day }.abbrev(/^.a/) #=> {"fast"=>"fast", "fas"=>"fast", "fa"=>"fast", "day"=>"day", "da"=>"day"}

17.查找二维数组首元素匹配的数组

s1 = [ "colors", "red", "blue", "green" ] 
s2 = [ "letters", "a", "b", "c" ] 
s3 = "foo" 
a = [ s1, s2, s3 ] 
a.assoc("letters") #=> [ "letters", "a", "b", "c" ] 
a.assoc("foo") #=> nil
a.assoc("a") #=> nil

18.清空数组

a = [ "a", "b", "c", "d", "e" ] a.clear #=> [ ]

19.数组元素调整

a = [ "a", "b", "c", "d" ] 
a.map { |x| x + "!" } #=> ["a!", "b!", "c!", "d!"] 
a #=> ["a", "b", "c", "d"]
a = [ "a", "b", "c", "d" ] 
a.map! {|x| x + "!" } 
a #=>  [ "a!", "b!", "c!", "d!" ]

20.一维数组转多维数组

a = [1, 2, 3, 4] 
a.combination(1).to_a #=> [[1],[2],[3],[4]] 
a.combination(2).to_a #=> [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]] 
a.combination(3).to_a #=> [[1,2,3],[1,2,4],[1,3,4],[2,3,4]] 
a.combination(4).to_a #=> [[1,2,3,4]] 
a.combination(0).to_a #=> [[]] # one combination of length 0 
a.combination(5).to_a #=> []  # no combinations of length 5

21.去除数组中的nil元素

[ "a", nil, "b", nil, "c", nil ].compact #=> [ "a", "b", "c" ]
[ "a", nil, "b", nil, "c" ].compact! #=> [ "a", "b", "c" ] 
[ "a", "b", "c" ].compact! #=> nil

22.数组统计

ary = [1, 2, 4, 2] ary.count #=> 4 
ary.count(2) #=> 2 
ary.count { |x| x%2 == 0 } #=> 3

23.数组循环

n次a = ["a", "b", "c"] 
a.cycle { |x| puts x } # print, a, b, c, a, b, c,.. forever. 
a.cycle(2) { |x| puts x } # print, a, b, c, a, b, c.

24.数组为空判断

[].empty? #=> true

25.改变数组元素

a = [ "a", "b", "c", "d" ] 
a.fill("x") #=> ["x", "x", "x", "x"] 
a.fill("z", 2, 2) #=> ["x", "x", "z", "z"] 
a.fill("y", 0..1) #=> ["y", "y", "z", "z"] 
a.fill { |i| i*i } #=> [0, 1, 4, 9] 
a.fill(-2) { |i| i*i*i } #=> [0, 1, 8, 27]

26.定位指定元素的位置

a = [ "a", "b", "c" ] 
a.index("b") #=> 1 
a.index("z") #=> nil 
a.index { |x| x == "b" } #=> 1

27.获取数组前n个元素

a = [ "q", "r", "s", "t" ] 
a.first #=> "q" 
a.first(2) #=> ["q", "r"]

28.多维数组向低维数组转换

s = [ 1, 2, 3 ] #=> [1, 2, 3] 
t = [ 4, 5, 6, [7, 8] ] #=> [4, 5, 6, [7, 8]] 
a = [ s, t, 9, 10 ] #=> [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10] 
a.flatten #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
a = [ 1, 2, [3, [4, 5] ] ] 
a.flatten(1) #=> [1, 2, 3, [4, 5]]
a = [ 1, 2, [3, [4, 5] ] ] 
a.flatten! #=> [1, 2, 3, 4, 5] 
a.flatten! #=> nil 
a #=> [1, 2, 3, 4, 5] 
a = [ 1, 2, [3, [4, 5] ] ] 
a.flatten!(1) #=> [1, 2, 3, [4, 5]]

29.数组替换

a = [ "a", "b", "c", "d", "e" ] 
a.replace([ "x", "y", "z" ]) #=> ["x", "y", "z"] 
a #=> ["x", "y", "z"]

30.插入元素到数组指定位置

a = %w{ a b c d } 
a.insert(2, 99) #=> ["a", "b", 99, "c", "d"] 
a.insert(-2, 1, 2, 3) #=> ["a", "b", 99, "c", 1, 2, 3, "d"]

31.数组元素拼接为指定格式字符串

[ "a", "b", "c" ].join #=> "abc" 
[ "a", "b", "c" ].join("-") #=> "a-b-c"

32.获取数组后n个元素

a = [ "w", "x", "y", "z" ]
a.last #=> "z"  
a.last(2) *#=> ["y", "z"]*

33.数组元素反转

[ "a", "b", "c" ].reverse #=> ["c", "b", "a"]
 [ 1 ].reverse #=> [1]
a = [ "a", "b", "c" ] 
a.reverse! #=> ["c", "b", "a"] 
a #=> ["c", "b", "a"]

34.数组从后向前循环

a = [ "a", "b", "c" ] a.reverse_each {|x| print x, " " } #=> c b a

35.定位数组元素最后一个出现的位置

a = [ "a", "b", "b", "b", "c" ] 
a.rindex("b") #=> 3 
a.rindex("z") #=> nil 
a.rindex { |x| x == "b" } #=> 3

36.从一个数组随机去n个元素

a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] 
a.sample #=> 7 
a.sample(4) #=> [6, 4, 2, 5]

37.随机打乱数组元素

a = [ 1, 2, 3 ] #=> [1, 2, 3] 
a.shuffle #=> [2, 3, 1]
a.shuffle(random: Random.new(1)) #=> [1, 3, 2]

38.数组排序

a = [ "d", "a", "e", "c", "b" ] 
a.sort #=> ["a", "b", "c", "d", "e"]  #升序排序
a.sort { |x,y| y <=> x } #=> ["e", "d", "c", "b", "a"]  #降序排序
a = [ "d", "a", "e", "c", "b" ] 
a.sort! #=> ["a", "b", "c", "d", "e"] 
a.sort! { |x,y| y <=> x } #=> ["e", "d", "c", "b", "a"]

39.二维数组行列倒转

a = [[1,2], [3,4], [5,6]] 
a.transpose #=> [[1, 3, 5], [2, 4, 6]]

40.数组去重

a = [ "a", "a", "b", "b", "c" ] 
a.uniq # => ["a", "b", "c"] 
b = [["student","sam"], ["student","george"], ["teacher","matz"]] 
b.uniq { |s| s.first } # => [["student", "sam"], ["teacher", "matz"]]
a = [ "a", "a", "b", "b", "c" ] a.uniq! # => ["a", "b", "c"]
b = [ "a", "b", "c" ]  b.uniq! # => nil
c = [["student","sam"], ["student","george"], ["teacher","matz"]] 
c.uniq! { |s| s.first } # => [["student", "sam"], ["teacher", "matz"]]

41.一次获取数组不同位置的元素

a = %w{ a b c d e f } 
a.values_at(1, 3, 5) # => ["b", "d", "f"] 
a.values_at(1, 3, 5, 7) # => ["b", "d", "f", nil] 
a.values_at(-1, -2, -2, -7) # => ["f", "e", "e", nil] 
a.values_at(4..6, 3...6) # => ["e", "f", nil, "d", "e", "f"]

42.多个一维数组组成二维矩阵

a = [ 4, 5, 6 ] 
b = [ 7, 8, 9 ]
[1, 2, 3].zip(a, b) #=> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
[1, 2].zip(a, b) #=> [[1, 4, 7], [2, 5, 8]] 
a.zip([1, 2], [8]) #=> [[4, 1, 8], [5, 2, nil], [6, nil, nil]]

43.合并两个数组并且去重

[ "a", "b", "c" ] | [ "c", "d", "a" ] #=> [ "a", "b", "c", "d" ]

44.combination

a= [1,2,3,4]a.combination(1).to_a#=> [[1],[2],[3],[4]]
a.combination(2).to_a#=> [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
a.combination(3).to_a#=> [[1,2,3],[1,2,4],[1,3,4],[2,3,4]]
a.combination(4).to_a#=> [[1,2,3,4]]
a.combination(0).to_a#=> [[]] # one combination of length 0
a.combination(5).to_a#=> []  # no combinations of length 5
  1. coerce
1.coerce(2) # => [2, 1] 
1.coerce(2.3) # => [2.3, 1.0] 
(4.5).coerce(2.3) # => [2.3, 4.5] 
(4.5).coerce(2) # => [2.0, 4.5]


二.String的用法
1.格式化对象到指定格式字符串

"%05d" % 123 #=> "00123"
"%-5s: %08x" % [ "ID", self.object_id ] #=> "ID  : 200e14d6"
"foo = %{foo}" % { :foo => 'bar' } #=> "foo = bar"

2.复制字符串

"Ho! " * 3 #=> "Ho! Ho! Ho! "
"Ho! " * 0 #=> ""

3.字符串拼接

"Hello from " + self.to_s #=> "Hello from main"
a = "hello "
a << "world"  #=> "hello world"
a.concat(33)  #=> "hello world!"

4.字符串比较

"abcdef" <=> "abcde"    #=> 1
"abcdef" <=> "abcdef"    #=> 0
"abcdef" <=> "abcdefg"  #=> -1
"abcdef" <=> "ABCDEF"    #=> 1
"abcdef".casecmp("abcde") #=> 1 
"aBcDeF".casecmp("abcdef") #=> 0
"abcdef".casecmp("abcdefg") #=> -1
"abcdef".casecmp("ABCDEF") #=> 0

5.获取子字符串

a = "hello there"
a[1] #=> "e"  
a[2, 3] #=> "llo"
a[2..3] #=> "ll"
a[-3, 2] #=> "er"
a[7..-2] #=> "her"
a[-4..-2] #=> "her"
a[-2..-4] #=> ""
a[11, 0] #=> ""
a[11] #=> nil
a[12, 0] #=> nil
a[12..-1] #=> nil
a[/[aeiou](.)\1/] #=> "ell"
a[/[aeiou](.)\1/, 0] #=> "ell"
a[/[aeiou](.)\1/, 1] #=> "l"
a[/[aeiou](.)\1/, 2] #=> nil
a[/(?[aeiou])(?[^aeiou])/, "non_vowel"] #=> "l"
a[/(?[aeiou])(?[^aeiou])/, "vowel"] #=> "e"
a["lo"] #=> "lo"
a["bye"] #=> nil

6.判断字符串是否只有ASCII字符

"abc".force_encoding("UTF-8").ascii_only? #=> true 
"abc\u{6666}".force_encoding("UTF-8").ascii_only? #=> false

7.统计字符串字节长度

"\x80\u3042".bytesize #=> 4 
"hello".bytesize #=> 5

8.首字母大写

"hello".capitalize #=> "Hello" 
"HELLO".capitalize #=> "Hello" 
"123ABC".capitalize #=> "123abc"

9.字符串居中

"hello".center(4) #=> "hello"
"hello".center(20) #=> "      hello        " 
"hello".center(20, '123') #=> "1231231hello12312312"

10.去除字符串尾部换行符或者指定字符

"hello".chomp #=> "hello" 
"hello\n".chomp #=> "hello" 
"hello\r\n".chomp #=> "hello" 
"hello\n\r".chomp #=> "hello\n" 
"hello\r".chomp #=> "hello" 
"hello \n there".chomp #=> "hello \n there" 
"hello".chomp("llo") #=> "he"

11.去除字符串尾部最后一个字符

"string\r\n".chop #=> "string"
"string\n\r".chop #=> "string\n"
"string\n".chop #=> "string"
"string".chop #=> "strin"
"x".chop.chop #=> ""

12.获取字符串第一个字符

a = "abcde" 
a.chr #=> "a"

13.清空字符

a = "abcde" 
a.clear #=> ""

14.统计字符串指定字符出现的个数

a = "hello world" a.count "lo" #=> 5
a.count "lo", "o" #=> 2
a.count "hello", "^l" #=> 4
a.count "ej-m" #=> 4
"hello^world".count "\\^aeiou" #=> 4
"hello-world".count "a\\-eo" #=> 4
c = "hello world\\r\\n"
c.count "\\" #=> 2
c.count "\\A" #=> 0
c.count "X-\\w" #=> 3

15.删除字符串指定字符

"hello".delete "l","lo" #=> "heo"
"hello".delete "lo" #=> "he"
"hello".delete "aeiou", "^e" #=> "hell"
"hello".delete "ej-m" #=> "ho"

16.字符串小写

"hEllO".downcase #=> "hello"

17.遍历字符串

"hello".each_char {|c| print c, ' ' }

18.判断字符串长度是否为

"hello".empty? #=> false 
" ".empty? #=> false 
"".empty? #=> true

19.替换字符串指定字符

"hello".gsub(/[aeiou]/, '*') #=> "h*ll*"
"hello".gsub(/([aeiou])/, '<\1>') #=> "hll"
"hello".gsub(/./) {|s| s.ord.to_s + ' '} #=> "104 101 108 108 111 "
"hello".gsub(/(?[aeiou])/, '{\k}') #=> "h{e}ll{o}"
'hello'.gsub(/[eo]/, 'e' => 3, 'o' => '*') #=> "h3ll*"

19-01.gsub案例(AaaBaa替换为aaa_baa)

"HelloWorld".gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2').gsub(/([a-z\d])([A-Z])/, '\1_\2').tr('-', '_').downcase#=> "hello_world"
"World".gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2').gsub(/([a-z\d])([A-Z])/, '\1_\2').tr('-', '_').downcase#=> "world"

20.判断字符串是否包含指定字符串

"hello".include? "lo" #=> true
"hello".include? "ol" #=> false
"hello".include? ?h #=> true

21.定位指定字符在字符串中的位置第一次出现的位置

"hello".index('e') #=> 1
"hello".index('lo') #=> 3
"hello".index('a') #=> nil
"hello".index(?e) #=> 1
"hello".index(/[aeiou]/, -3) #=> 4

最后一次出现的位置"hello".rindex('e') #=> 1

"hello".rindex('l') #=> 3
"hello".rindex('a') #=> nil
"hello".rindex(?e) #=> 1
"hello".rindex(/[aeiou]/, -2) #=> 1

22.字符串替换

s = "hello" #=> "hello"
s.replace "world" #=> "world"

23.插入字符到指定位置

"abcd".insert(0, 'X') #=> "Xabcd"
"abcd".insert(3, 'X') #=> "abcXd"
"abcd".insert(4, 'X') #=> "abcdX"
"abcd".insert(-3, 'X') #=> "abXcd"
"abcd".insert(-1, 'X') #=> "abcdX"

24.字符串对齐左对齐

"hello".ljust(4) #=> "hello" 
"hello".ljust(20) #=> "hello              " 
"hello".ljust(20, '1234') #=> "hello123412341234123"
右对齐"hello".rjust(4) #=> "hello" "hello".rjust(20) #=> "              hello" 
"hello".rjust(20, '1234') #=> "123412341234123hello"

25.去除字符串空格

"  hello  ".lstrip #=> "hello  " 
"hello".lstrip #=> "hello"
"  hello  ".rstrip #=> "  hello" 
"hello".rstrip #=> "hello"
"    hello    ".strip #=> "hello" 
"\tgoodbye\r\n".strip #=> "goodbye"

26.字符串匹配

'hello'.match('(.)\1') #=> #
'hello'.match('(.)\1')[0] #=> "ll" 
'hello'.match(/(.)\1/)[0] #=> "ll" 
'hello'.match('xx') #=> nil

27.字符串加一

"abcd".succ #=> "abce"
"THX1138".succ #=> "THX1139"
"<>".succ #=> "<>"
"1999zzz".succ #=> "2000aaa"
"ZZZ9999".succ #=> "AAAA0000"
"***".succ #=> "**+"

28.获取字符指定ASCII码值

"a".ord #=> 97

29.分割字符串到指定数组

str.partition(sep) → [head, sep, tail]
str.partition(regexp) → [head, match, tail]
"hello".partition("l") #=> ["he", "l", "lo"]
"hello".partition("x") #=> ["hello", "", ""]
"hello".partition(/.l/) #=> ["h", "el", "lo"]
"hello".rpartition("l") #=> ["hel", "l", "o"]
"hello".rpartition("x") #=> ["", "", "hello"]
"hello".rpartition(/.l/) #=> ["he", "ll", "o"]

30.追加字符串到指定字符串最前面

a = "world" a.prepend("hello ") #=> "hello world" 
a #=> "hello world"

31.反转字符串

"stressed".reverse #=> "desserts"

32.分割字符串

" now's  the time".split #=> ["now's", "the", "time"] 
" now's  the time".split(' ') #=> ["now's", "the", "time"] 
" now's  the time".split(/ /) #=> ["", "now's", "", "the", "time"]
"1, 2.34,56, 7".split(%r{,\s*}) #=> ["1", "2.34", "56", "7"] 
"hello".split(//) #=> ["h", "e", "l", "l", "o"] 
"hello".split(//, 3) #=> ["h", "e", "llo"] 
"hi mom".split(%r{\s*}) #=> ["h", "i", "m", "o", "m"] 
"mellow yellow".split("ello") #=> ["m", "w y", "w"] 
"1,2,,3,4,,".split(',') #=> ["1", "2", "", "3", "4"] 
"1,2,,3,4,,".split(',', 4) #=> ["1", "2", "", "3,4,,"] 
"1,2,,3,4,,".split(',', -4) #=> ["1", "2", "", "3", "4", "", ""] 
"".split(',', -1)* #=> []*
"World".split('r')[0]#=> "Wo"
"World".split('r')[1]#=> "ld"

33.去除字符串中重复的字符

"yellow moon".squeeze #=> "yelow mon" 
"  now  is  the".squeeze(" ") #=> " now is the" 
"putters shoot balls".squeeze("m-z") #=> "puters shot balls"

34.大小写互换

"Hello".swapcase #=> "hELLO"
"cYbEr_PuNk11".swapcase #=> "CyBeR_pUnK11"

35.字符串转大写

"hEllO".upcase #=> "HELLO"

36.字符串循环

"a8".upto("b6") {|s| print s, ' ' } #=> a8 a9 b0 b1 b2 b3 b4 b5 b6
"9".upto("11").to_a #=> ["9", "10", "11"] 
"25".upto("5").to_a #=> [] 
"07".upto("11").to_a #=> ["07", "08", "09", "10", "11"]

37.判断字符串编码是否正确

"\xc2\xa1".force_encoding("UTF-8").valid_encoding? #=> true 
"\xc2".force_encoding("UTF-8").valid_encoding? #=> false 
"\x80".force_encoding("UTF-8").valid_encoding? #=> false

三、Ruby中Enumerable#inject用法示范
Enumerable#inject是Ruby核心库中的一个简洁而且强大的API,今天读到一段简洁的代码之后,对这个API产生了浓厚的兴趣,索性搜寻一下资料,总结一下它的用法。
代码如下:
Java代码

def text_at(*args)
  args.inject(@feed) { |s, r| s.send(:at, r)}.inner_text
end

这段代码完成的功能是:取出XML文件中某子元素的文本内容,它是用nokogiri库来完成这个功能的。关于Nokogiri库API(at(), inner_text())的细节我们不谈,只是用这段代码来引起你对inject的兴趣,现在我们来看inject的用法。
Enumerable#inject是很多Ruby高手喜欢的API,因此将来读Ruby也会经常遇到,即使有的用法不能完全理解,也要先混个脸熟,使用场景见多了就自然理解了。

  1. 数字求和
    Inject最常见的用法就是这一个了,假定你有一个内容为数字的数组,你可以像下面这样对它求和:
    Ruby代码
irb(main):001:0> [1, 2, 3, 4, 5].inject(0) { |sum, e| sum + e }
=> 15

或者像这样:
Ruby代码

irb(main):002:0> (1..5).inject(0) { |sum, e| sum + e }
=> 15

用区间或者数组在这里没有分别,Ruby会自动转换。Inject在这里接受一个方法参数和一个block. 对数组中的每一个元素,block都执行一次。第一次执行block的时候,inject接收的方法参数被作为block的第一个参数,而block的第二个参数则是数组的第一个元素。第二次执行block的时候,情况就有了变化,这也是inject神奇的地方。这时候block的第一个参数则是block上一次执行的返回值(block的最后一个表达式),第二个参数则是数组的第二个元素,后面的三次执行方式与第二次相同,这样我们就计算出了数组元素之和。事实上,上面的代码还可以更简洁一些:
Ruby代码

irb(main):006:0> [1, 2, 3, 4, 5].inject { |sum, e| sum + e }
=> 15

这段代码可以计算出相同结果的原因是:inject的方法参数是可选的,如果不提供的话,Ruby默认将数组的第一个元素作为block第一次执行时候的第一个参数,在这种情况下,block一共需要执行4次,比传入默认参数的形式少执行一次。

  1. 转换数据结构
    2.1生成Hash:
    Java代码
hash = [[:first_name, 'Shane'], [:last_name, 'Harvie']].inject({}) do |result, element|
  result[element.first] = element.last
  result
end

当然这种用法也有别的形式,并不一定需要用到inject,比如:
Java代码

Hash[*[[:first_name, 'Shane'], [:last_name, 'Harvie']].flatten]

可以达到相同目的而代码更简洁。
2.2 过滤数组:
Ruby代码

arr = [1, 2, 3, 4, 5, 6].inject([]) do |r, e|
   r << e.to_s if e % 2 == 0
   r
end

当然这种用法也有不使用inject的等价方式:
Java代码

[1, 2, 3, 4, 5, 6].select { |e| e % 2 == 0 }.collect { |e| e.to_s } # => ["2", "4", "6"]

具体用哪一种就是萝卜青菜,各有所爱了。

  1. 更高级的用法
    先看一段代码:
    Ruby代码
class Recorder
  # undefine any instance methods except methods start from __
  # and inspect/to_str/object_id
  instance_methods.each do |meth|
    undef_method meth unless meth =~ /^(__|inspect|to_str)|object_id/
  end

  # store messages sent to the Recorder object
  # that's why it's called Recorder
  def method_missing(sym, *args)
    messages << [sym, args]
    self
  end

  # getter of instance variable messages
  def messages
    @messages ||= []
  end
end

代码中比较难懂的部分已经加了注释,类Recorder完成的功能是记录所有发送给它对象的消息(Ruby中对象调用通常称作向对象发送消息)。下面我们再打开类Recorder,定义另一方法来展示这些保存的消息:
Ruby代码

class Recorder
  def play_for(obj)
    messages.inject(obj) do |result, msg|
      result.send msg.first, *msg.last
    end
  end
end

在这个方法中,我们用到了inject, 它向传入的对象obj调用保存的消息,并传入之前调用者传入的所有参数。下面的代码展现了它的用法:
Ruby代码

recorder = Recorder.new
recorder.methods.sort
recorder.play_for(String)

它实现了对String对象(你应该可以想起来,Ruby的类也是对象)调用#methods(), 然后对#methods返回结果调用#sort().
其实上面这个Recorder示例和本文开头的那个范例原理相同,前一个调用可以响应第一个消息,返回的结果则分别可以响应接下来的消息,对比这两个示例可以对Enumerable#inject的强大之处有所体会。

参考:http://blog.jayfields.com/2008/03/ruby-inject.html

相关文章

  • Ruby关于数组的的一些实用方法

    一、Array的用法1.新建数组 2.元素访问 3.获取数组信息 4.向数组添加元素 5.从数组删除元素 6.遍历...

  • ruby 数据类型

    1. Ruby 字符串(String) 2. Ruby 数组 3. Ruby 哈希 哈希的内置方法 4. Ruby...

  • Ruby常用方法(3)

    Ruby对象数组按属性排序1 .Rails里,我们可以用sort_by方法对一个Ruby对象数组按照某个属性进行排...

  • Ruby 数组

    数组 数组的循环 Ruby 中提供了 each 方法. 语法如下: each 后面在 do ~ end 之间的部...

  • ruby创建多维数组的方法

    或者用下面的方法:

  • record 5 go 中的数组

    一、数组的简单实用 数组创建的方法,及一些特点直接看例子即可请见下图 那么看这个例子,我们总结一下,数组的创建1、...

  • Ruby 关于方法调用的一些补充

    把数组分解为参数 在调用方法时, 如果以*数组这样的形式指定参数, 这时传递给方法的就不是数组本身, 而是数组的各...

  • reduce实现多个实用的数组方法

    使用reduce实现数组自身的以及其他实用的方法。此处不考虑性能,仅仅通过reduce去实现一些方法以体现redu...

  • 数组及字符串方法

    数组实用方法 1.Array.from()方法从一个类似数组或可迭代对象中创建一个新的数组实例。 2.filter...

  • 关于js数组的一些方法

    添加(返回新的数组长度) 末尾添加 arr.push(els) 开头添加 arr.unshift(els) 删除(...

网友评论

本文标题:Ruby关于数组的的一些实用方法

本文链接:https://www.haomeiwen.com/subject/hmeirxtx.html