December 12, 2015 by Daniel P. Clark

Ruby: Arrays by Example

Arrays are Ruby’s most used collection type.  I will use very little description as I give examples for the many different ways to work with Arrays.

Different ways to create an empty Array

Filling an Array

Insertion

Boolean/Truthiness

Transformations

Slicing

Adding

Replace & Remove

Selecting

Mapping

Reduce with compounded result

Counting

Array()

As you can see Array() tries to call to_ary first, to_a if that doesn’t work, and just wraps the object in an Array if neither of those methods are defined.

The Ws

As you can see the Ws are great if you want to have either kind of quotation marks within your string items.

In closing

In all of the examples above I’ve shown the output but haven’t explicitly revealed whether the methods change the Array they’re called on or just return an Array result.  Please experiment for yourself in an irb terminal to find out more.  Typically any method ending with an exclamation point (!) changes the Array itself.

Feel free to check out my other related posts on Different Collection Types in RubyWhen to use Ampersand and/or Colon with Proc, Map, and Inject , and comment any useful Array method usages and tricks!  I may add more examples for Array here so be sure to check back!

As always I hope you’ve enjoyed this!  Please comment, share, subscribe to my RSS Feed, and follow me on twitter @6ftdan!

God Bless!
-Daniel P. Clark

Image by Tom Blackwell via the Creative Commons Attribution-NonCommercial 2.0 Generic License

#array#collection#example#examples#ruby
  • Fantastic resource! Bookmarked

  • Ketan Shukla

    This is such a fantastic article! Worthy of being bookmarked for reference! Thank you for this Dan!

  • Cameron Seright

    Amazing resource, I learned so much! Thank you, Daniel. Here I was thinking I knew Arrays well =]