Home > OS >  How to remove square brackets (only) from an array?
How to remove square brackets (only) from an array?

Time:05-09

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!

CodePudding user response:

hash.values_at(*FIELDS)

The asterisk is called the splat operator. Doc

CodePudding user response:

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.

  • Related