6

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?

overtone
  • 1,063
  • 3
  • 16
  • 23
  • http://stackoverflow.com/questions/2637419/understanding-ruby-array-sort reading this now but still not sure if it applies to what I'm trying to do – overtone Aug 23 '11 at 13:42

2 Answers2

21

You can use the select method.

@x = @my_array_of_stuff.select {|v| v["single-key"]["object-identifier"] > 3}
Gazler
  • 83,029
  • 18
  • 279
  • 245
0
collection = [
  {a:1, b:2, c:3},
  {a:2, b:3, c:4}
]
where = {a:1}
collection.select{|item|
  where.map{|k,v|
    item[k] == v ? true : nil
  }.compact.length == where.length
}
Gabe Coyne
  • 331
  • 3
  • 5
  • 2
    While code-only answers are not forbidden, please understand that this is a Q&A community, rather than a crowd-sourcing one, and that, usually, if the OP understood the code being posted as an answer, he/she would have come up with a similar solution on his/her own, and wouldn't have posted a question in the first place. The same principle also applies further to any future readers who might be unfamiliar with the code being presented. As such, please provide context to your answer and/or code by explaining *how* and/or *why* it works. – CosmicGiant Jul 27 '16 at 02:01