RCA
RCA

Reputation: 508

Use array for keys in Ruby, then add two options per key

edit Duh, hashes require unique keys (unless you're doing something weird, as in the comments). Keeping this up in case someone else makes the same mistake.

I've got an array of column names, and would like to end up with a hash where those column names form keys, each appearing twice in the hash with different values each time. An example is probably easier to understand:

cols = ["test", "data"] # input
{"test" => "asc", "test" => "desc", "data" => "asc", "data" => "desc"} #expected output

I tried to use map, but as I've set it up it's nesting too much:

cols.map { |c| [c, ["asc", "desc"]] }.to_h
> {"test" => ["asc", "desc"], "data" => ["asc", "desc"]}

cols.map { |c| [[c, "asc"], [c, "desc"]] }.to_h
> {["test", "asc"]=>["test", "desc"], ["data", "asc"]=>["data", "desc"]}

Upvotes: 0

Views: 58

Answers (2)

RCA
RCA

Reputation: 508

What I ended up doing was an array of arrays.

cols.map { |c| [c, "asc"] }.append(*cols.map { |c| [c, "desc"] })
> [["test", "asc"], ["data", "asc"], ["test", "desc"], ["data", "desc"]]

This has the benefit of not breaking the laws of Ruby.

Upvotes: 0

user1934428
user1934428

Reputation: 22225

What you want, contradicts the definition of a Hash, where keys need to be unique.

If one key is supposed to have several values, I suggest that you model those values as either arrays (as in your first solution), or as Set.

Hence if you resulting Hash is called h, you could make a structure so that

h['test'] 

is a Set having the elements "asc" and "desc":

require 'set'
...
h = cols.map { |c| [c, Set.new(["asc", "desc"])] }.to_h

Upvotes: 1

Related Questions