loading...

Arrays in Ruby

mariel profile image mariel ・2 min read

A previous post discussed some basic array properties. This one drills down a little into the syntax for Ruby.

Making an Array
Arrays can be initialized with square brackets ([ ]). This is called a literal initialization. Its values are separated by commas and their index begins at zero.

[“dog”, “bird”, “cat”]

Dog is at index 0, bird is at index 1, etc.

You can access what is at a specific index number just by using that number.

pets = ["dog", "cat", "bird"]
=> ["dog", "cat", "bird"]
pets[2]
=> "bird"

You can also assign elements to a specific index number, and the array will grow to accommodate. Index numbers with no content are “nil.”

pets[4] = "hamster"
=> "hamster"
pets
=> ["dog", "cat", "bird", nil, "hamster"]

Array Methods
Arrays are objects so there are methods that can be directly attached to them:

  • .first and .last will show you the first or last element
  • .length will tell you how many elements there are
  • .include[x] will tell you if x is included in the array (true or false)
  • .find_index(x) will tell you at what index x is located
  • .push adds to the end of an array
  • .pop pops an element off the end
  • .shift adds to the beginning of an array
  • << does the same thing as push; it’s referred to as “shovel”

To convert the elements in an array into a string:

[“d”, “o”, “g”].join
=> dog

To convert elements in an array into a string but separate them by something, like a hyphen:

[“d”, “o”, “g”].join(“-”)
=> d-o-g

Posted on by:

mariel profile

mariel

@mariel

Dev. I love dogs, cookies, and learning new things.

Discussion

pic
Editor guide