Skip to content

Instantly share code, notes, and snippets.

@meaganewaller
Created January 1, 2015 02:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meaganewaller/762e6b4042f7d836ebde to your computer and use it in GitHub Desktop.
Save meaganewaller/762e6b4042f7d836ebde to your computer and use it in GitHub Desktop.
Ruby arrays
>> vowels = [ "a", "e", "i", "o", "u"]
>> vowels[0]
=> "a"
>> vowels.size
=> 5
>> [1, 2] << 3
=> [1, 2, 3]
>> [1, 2, 3].push(4)
=> [1, 2, 3, 4]
>> [1, 2, 3] << [3, 2, 1]
=> [1, 2, 3, [3, 2, 1]]
>> array = [1, 2, 3]
>> array.pop
=> 3
>> array
=> [1, 2]
>> array = [1, 2, 3, 4]
>> array.shift
=> 4
>> array
=> [1, 2, 3]
>> array = [ 1, 2, 3, 4]
>> array.delete(1)
=> 1
>> array
=> [2, 3, 4]
>> array.delete_at(2)
=> 4
>> array
=> [2, 3]
>> [1, 2, 3].reverse
=> [3, 2, 1]
>> [1, 2, 3].rotate
=> [2, 3, 1]
>> [1, 2, 3].rotate(-2)
=> [2, 3, 1]
>> ["a", "a", "b", "c", "b"].uniq
=> ["a", "b", "c"]
>> [1, 2, 3].include?(2)
=> true
>> [1, 2, 3].include?("a")
=> false
>> [1, 2, 3, 4, 5, 6].each { |num| puts num }
1
2
3
4
5
6
>> [1, 2, 3, 4, 5, 6].reverse_each { |num| puts num }
6
5
4
3
2
1
>> ["a", "b", "c", "d"].each_with_index do |letter, index|
>> puts "#{letter}: #{index}"
a: 0
b: 1
c: 2
d: 3
>> our_array = [ "a", 1, 1.4567, false]
>> odds = Array.new([1, 3, 5, 7])
=> [1, 3, 5, 7]
>> array = Array.new(5)
=> [ nil, nil, nil, nil, nil]
>> Array.new(5, "a")
=> ["a", "a", "a", "a", "a"]
>> Array.new(3, 0)
=> [0, 0, 0]
>> %W{1 2 3 4}
=> [1, 2, 3, 4]
>> %w{This is an array}
=> ["This", "is", "an", "array"]
>> name = "meagan"
>> %W{My name is #{name}}
=> ["My", "name", "is", "meagan"]
>> %w{My name is #{name}}
=> ["My", "name", "is", "\#{name}"]
>> months = []
>> months[5]
=> nil
>> months[5] = "june"
=> [nil, nil, nil, nil, nil, "june"]
>> [1, 2, 3, 4][-1]
=> 4
>> ["a", "e", "i", "o", "u"][-2]
=> "o"
>> [1, 2, 3][-4]
=> nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment