7 tricks when working with arrays in Ruby

Original author: Christophe
  • Transfer
  • Tutorial
ruby arrays

This article describes some interesting tricks on how to effectively use and work with arrays in Ruby. Of course, there is RubiDoc and many other resources that describe in detail all the available methods, but here I want to share exactly the ways of using it.


1. How to check or an array contains all the elements of another array


For example, you want to check or all imported emails are already in the contact list:
imported_emails = [ 'john@doe.com', 'janet@doe.com' ]
existing_emails = [ 'john@doe.com', 'janet@doe.com' , 'fred@mercury.com' ]
puts 'already imported' if (imported_emails - existing_emails).empty?

Launch in IRB :
already imported
=> nil


2. How to find common elements in two arrays


For example, if you need to find common tags in two different posts:
tags_post1 = [ 'ruby', 'rails', 'test' ]
tags_post2 = [ 'test', 'rspec' ]
common_tags = tags_post1 & tags_post2

Launch in IRB :
=> ["test"]

3. How to connect two arrays without duplicating duplicate elements


followeds1 = [ 1, 2, 3 ]
followeds2 = [ 2, 4, 5 ]
all_followeds =  followeds1 | followeds2

Launch in IRB :
=> [1, 2, 3, 4, 5]

4. How to sort a hash array


For example, you get data from some kind of API, in the form of an array of hashes:
data = [
 {
    name: 'Christophe',
    location: 'Belgium'
 },
 {
    name: 'John',
    location: 'United States of America'
 },
 {
    name: 'Piet',
    location: 'Belgium'
 },
 {
    name: 'François',
    location: 'France'
 }
]

When displayed, you want to sort by location field, then do this:
data.sort_by { |hsh| hsh[:location] }

Launch in IRB :
=> [
{: name => “Christophe”,: location => “Belgium”},
{: name => “Piet”,: location => “Belgium”},
{: name => “François ",: Location =>" France "},
{: name =>" John ",: location =>" United States of America "}
]


5. How to get unique elements of an array by a certain attribute


For example, you want to show random products on the main page, but so that each product is taken from only one category:
Product = Struct.new(:id, :category_id)
products = [
 Product.new(1, 1),
 Product.new(2, 2),
 Product.new(3, 3),
 Product.new(4, 1),
 Product.new(5, 3),
 Product.new(6, 5),
]
products = products.uniq &:category_id

Launch in IRB :
=> [
#,
#,
#,
#
]


6. How to filter string elements of an array


For example, you may have an array with the names of the books that you want to filter by some keyword:
books = [
 'The Ruby Programming Language',
 'Programming Ruby 1.9 & 2.0: The Pragmatic Programmers\' Guide (The Facets of Ruby)',
 'Practical Object-Oriented Design in Ruby: An Agile Primer',
 'Eloquent Ruby',
 'Ruby on Rails Tutorial: Learn Web Development with Rails'
]
books = books.grep(/[Rr]ails/)

Launch in IRB :
=> ["Ruby on Rails Tutorial: Learn Web Development with Rails"]

7. How to always return an array


For example, you have a method that can return a list of products or a single product. To ensure that the return value is always an array, you can use Array () or [*]:
def method
 # …
 [*products]
end

Also popular now: