Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>people.select {|person| person.any? {|k, v| %w[location hometown].include?(k) &amp;&amp; /New York/ =~ v['name'] }} </code></pre> <p>This basically says the following: select all entries in the array for which the following condition is true. The condition is: is it true for any of the key-value pairs that the key is either <code>'hometown'</code> or <code>'location'</code> and the <code>name</code> property of the value belonging to that key matches the Regexp <code>/New York/</code>?</p> <p>However, your object model seems to be in a serious need of refactoring. In fact, the main problem is that your object model isn't even an object model, it's a hash and array model.</p> <p>Here's what I mean by a proper object model:</p> <pre><code>class Person attr_reader :name, :location, :hometown def initialize(name, location=nil, hometown=nil) @name, @location, @hometown = name, location, hometown end def cities return @location, @hometown end end class City attr_reader :id, :name def initialize(id, name) @id, @name = id, name end def =~(other) name =~ other end end nyc = City.new(12746342329, 'New York, New York') brooklyn = City.new(43453644, 'Brooklyn, New York') miami = City.new(12746342329, 'Miami, Florida') queens = City.new(12746329, 'Queens, New York') john = Person.new('John Doe', nyc, brooklyn) jane = Person.new('Jane Doe', miami, queens) people = [john, jane] </code></pre> <p>If you have such a proper object model, your code becomes much cleaner, because instead of teasing apart the nuts of bults of a nested maze of hashes and arrays, you have nice little objects that you can simply ask some questions:</p> <pre><code>people.select {|person| person.cities.any? {|city| city =~ /New York/ }} </code></pre> <p>You can almost read this like English: from the array select all people for which any of their cities matches the Regexp <code>/New York/</code>.</p> <p>If we improve the object model further, it gets even better:</p> <pre><code>class Person def lived_in?(pattern) cities.any? {|city| city =~ pattern } end end people.select {|person| person.lived_in?(/New York/) } </code></pre> <p>This basically says "From the people, select the ones which at one time lived in New York". That's much better than "from the people select all for which the first element of the key value pair is either the string <code>'hometown'</code> or the string <code>'location'</code> and the second element of the key value pair matches the Regexp <code>/New York/</code>".</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload