0

I have an array stored in a constant like this:

FIELDS = ["first_name", "last_name", "occupation"]

I need to remove the square brackets only, it will look like this:

"first_name", "last_name", "occupation"

Does anyone have any ideas?

Thanks. :-)

For a little more context:

I have a complicated hash where I need to grab specific values from. My idea was to have the key of each value stored as an array, so I could then so

hash.values_at("first_name", "last_name", "occupation")

But that won't work with the square brackets from the array, hence my question!

I may be going around this the wrong way, however!

steenslag
  • 79,051
  • 16
  • 138
  • 171
MomoMomo
  • 1
  • 1
  • 1
    Can you explain what you are actually looking for? You second line is only valid as an implicit `Array` during assignment. Are you maybe looking for `"\"first_name\",\"last_name\",\"occupation\""` or `"first_name, last_name, occupation"`? The question is a bit unclear as to the desire or the reasoning. – engineersmnky May 09 '22 at 13:02
  • Hi @engineersmnky, I've added some more context to my question. :-) – MomoMomo May 09 '22 at 13:11

2 Answers2

5
hash.values_at(*FIELDS)

The asterisk is called the splat operator. Doc

steenslag
  • 79,051
  • 16
  • 138
  • 171
0

Edit: Now that you've added some context to your question, I see you'd like to do something quite different.

Here is how you would iterate (loop) over a list of key hashes to get their values:

EXAMPLE_HASH = { 'first_name' => 'Jane', 'last_name' => 'Doe', 'occupation' => 'Developer', 'other_key' => 'Dont return this' }.freeze
FIELDS       = ['first_name', 'last_name', 'occupation'].freeze # Actually keys.

results = FIELDS.map{ |key|
  EXAMPLE_HASH[key]
}

=> ["Jane", "Doe", "Developer"]

Or more succinctly:

EXAMPLE_HASH = { 'first_name' => 'Jane', 'last_name' => 'Doe', 'occupation' => 'Developer', 'other_key' => 'Dont return this' }.freeze
FIELDS       = ['first_name', 'last_name', 'occupation'].freeze # Actually keys.

results = EXAMPLE_HASH.values_at(*FIELDS)

=> ["Jane", "Doe", "Developer"]

This is a very odd thing to do as the array doesn't actually have those square brackets in reality, it's just how the array prints out to give an observer the clue that it is any array. So you can't ever actually "remove" those square brackets from an array, since they aren't there to begin with. You could potentially override the to_s (and inspect?) methods on the Array class so it would print out differently. But assuming you want a string as the output instead, this would accomplish the task:

FILEDS = ["first_name", "last_name", "occupation"]

fields_as_string = "\"#{FILEDS.join('", "')}\""

=> "\"first_name\", \"last_name\", \"occupation\""

However, it's not clear if you want a string as the output, nor is it clear if you're happy with the double-quotes being escaped in the string.

BenFenner
  • 982
  • 1
  • 6
  • 12