Skip to content

Instantly share code, notes, and snippets.

@ivan22
Created May 17, 2014 03:23
Show Gist options
  • Select an option

  • Save ivan22/810d522cc0521f840275 to your computer and use it in GitHub Desktop.

Select an option

Save ivan22/810d522cc0521f840275 to your computer and use it in GitHub Desktop.
List of array functions

Offical Documentation

Ruby 2.0 Array: http://www.ruby-doc.org/core-2.0.0/Array.html
Ruby 2.0 Enumerable: http://www.ruby-doc.org/core-2.0.0/Enumerable.html

2 Arrays Comparison and Operation

[1,2,3] - [1,2,3] # returns []
[1,2,3] & [1,2,3,4] # returns [1,2,3]

Sorting

  • Returns a new array created by sorting self.
a = [ "d", "a", "e", "c", "b" ]
a.sort                    #=> ["a", "b", "c", "d", "e"]
a.sort { |x,y| y <=> x }  #=> ["e", "d", "c", "b", "a"]

Joining

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

Prepending & Post-pending

a = [ "b", "c", "d" ]
a.unshift("a")   #=> ["a", "b", "c", "d"]
a.push("e") #=> ["a", "b", "c", "d", "e"]

Others

a = [ "b", "c", "d" ]
a.sample # => randomly gives an element
a.sample(2) # gives 2 elements at random
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment