Search code examples
rubysortinghashmetaprogrammingblock

Generating Blocks at Runtime to Search Multiple Parameters


I have a database that consists of an array of hash entries.

I'd like to sort this database based on parameters taken from the command line. If there is only one option this is easy:

dbArray.sort_by! { |record| record[ARGV[0]] }

However, when there are multiple sorting criteria, I'm not sure how to dynamically generate the block I want to pass to sort_by! here. Basically, I want to generate the code

dbArray.sort_by! { |record| [record[ARGV[0]], . . . ,  record[ARGV[N]]] }

for as many arguments as I have, but I don't know how to do this when I won't know how many arguments there are until runtime, short of doing something crazy like building a string and calling eval.


Solution

  • Sounds like you're looking for Hash#values_at:

    values_at(key, ...) → array

    Return an array containing the values associated with the given keys.

    So given a hash like this:

    h = { :a => :b, :c => :d, :e => :f }
    

    you can do this:

    a = [ :a, :e ]
    h.values_at(*a)
    # [:b, :f]
    

    In your case, you'd have something like this:

    dbArray.sort_by! { |record| record.values_at(*ARGV) }