× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

How to Filter Arrays of Data in Ruby

Dan Draper
Jul 23, 2015
<p>Often when writing Ruby programs, either in Rails or say as part of a script, its useful to be able to select or filter data in Ruby itself. While we would usually do this in the database (say via ActiveRecord) a database isn't always available. For example, we might want to load data from a CSV.</p> <p><strong>Filtering Arrays</strong></p> <p>To filter an array we can use select with a block. It looks something like this:</p> <pre><code class="language-ruby">array = [ 3, 4, 7, 12 ] result = array.select do |elem| elem &gt; 5 end</code></pre> <p>In this example we are using a block (indicated by the do) to tell the select method how to filter the array. You can think of a block a bit like a method and it has an argument, specified between the pipe ("|") symbols. The argument can be called whatever you like and in this case I've called it elem.</p> <p>This condition is saying we want to select or keep all elements in the array that are more than 5.</p> <p>Our result will be:</p> <pre><code class="language-ruby">result # =&gt; [ 7, 12 ]</code></pre> <p>Now imagine, we had an array of hashes! We might imagine this being the result of reading from a CSV:</p> <pre><code class="language-ruby">array = [ { name: 'Dan', score: 100 }, { name: 'Mike', score: 57 }, { name: 'Jill', score: 120 } ]</code></pre> <p>I want to filter my array to keep users where the score is more than or equal to 100. I could do:</p> <pre><code class="language-ruby">result = array.select do |hash| hash[:score] &gt;= 100 end</code></pre> <p>And as you might expect, the result will be:</p> <pre><code>[ { name: 'Dan', score: 100 }, { name: 'Jill', score: 120 } ]</code></pre> <p>Neat, huh!?</p> <p>Blocks can also be expressed using curly braces rather than do and end. So the below is equivalent:</p> <pre><code class="language-ruby">result = array.select { |hash| hash[:score] &gt;= 100 }</code></pre> <p>Though it's generally recommended to only use curly braces if you're using just 1 line.</p> <p><em>Happy Filtering!</em></p>
comments powered by Disqus