[Ruby] Ruby's several methods on arrays

Document link: ruby document address

delete()

  • Introduction:

Delete the selected item equal to obj from self. Returns the last deleted item, if no match is found, returns nil. If an optional code block is given, if the item is not found, the result of the code block is returned. (To remove the nil element and get an informative return value, use #compact!)

  • String example:

“(aa11234[s]d)d”.delete("()[]") => “aa11234sdd”

  • Array example:

pry(main)> a = [12,3,5]
=> [12, 3, 5]
pry(main)> a.delete(3)
=> 3
pry(main)> a
[12, 5]

group_by()

  • use

pry(main)> [{a:23,n:3},{a:12,d:3},{a:11}].group_by{|item| item[:a]}
=> {23=>[{:a=>23, :n=>3}], 12=>[{:a=>12, :d=>3}], 11=>[{:a=>11}]}

sort()

  • Simple example:

pry(main)> [3,3,4,3,2,1,0,34,12,121].sort
=> [0, 1, 2, 3, 3, 3, 4, 12, 34, 121]

  • Specify column sorting:

pry(main)> [{a:23,n:3},{a:12,d:3},{a:11}].sort{|item| item[:a]}
=> [{:a=>11}, {:a=>12, :d=>3}, {:a=>23, :n=>3}]

reverse

  • Sort extension

pry(main)> [{a:23,n:3},{a:12,d:3},{a:11}].sort{|item| item[:a]}.reverse
=> [{:a=>23, :n=>3}, {:a=>12, :d=>3}, {:a=>11}]

Guess you like

Origin blog.csdn.net/m0_46537958/article/details/108602252