Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby array equivalent of active record.where(criteria)

This may be a really long stretch but would make life a fair bit easier if it existed.

Heres the scenario any case. I have an array of hashes with one key whos value is another hash........Yeah, I know.

Heres a better explanation:

@myArrayOfStuff[0]
@myArrayOfStuff[0]["single-key"]
@myArrayOfStuff[0]["single-key"]["object-identifier"]

The first returns a hash. The second would return an object (called page in my case but example uses different names) The third returns whatever variable I have reference as object-identifier.

Simple enough.

What I'd like to do is pick make another array where object-identifiers value is not nil or is greater than x. Something Similar to the activerecord.where method.

@x = @myArrayOfStuff.where(["single-key"]["object-identifier"]) > 3orwhatever

Obviously this doesn't work as the syntax is attrocious. But is there another way of going about it? Another route to try might possibly be to sort the array by this variable. Something like

@x = @myArrayOfStuff.sort {|x,y| y <=> x } 

However I dont really understand whats going on with ruby's sort method. Can anyone help?

like image 669
overtone Avatar asked Aug 23 '11 13:08

overtone


People also ask

What does .first mean in Ruby?

Ruby | Array class first() function first() is a Array class method which returns the first element of the array or the first 'n' elements from the array.

What does .select do in Ruby?

Array#select() : select() is a Array class method which returns a new array containing all elements of array for which the given block returns a true value. Return: A new array containing all elements of array for which the given block returns a true value.

What is associative array in Ruby?

Ruby | Array assoc() function The assoc() function in Ruby is used to search through an array of arrays whose first element is compared with the index of the function and return the contained array if match found otherwise return either nil or vacant.

Is ActiveRecord an ORM?

ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code.


1 Answers

You can use the select method.

@x = @my_array_of_stuff.select {|v| v["single-key"]["object-identifier"] > 3}
like image 193
Gazler Avatar answered Sep 27 '22 21:09

Gazler