1

I would like to know if ruby has a builtin method to do the following.

from this array:

array = [:foo, :bar]

and this method:

def content_for_key key
  return :baz if key == :foo
  return :qux if key == :bar
end

and this call:

array.some_built_in_ruby_method(&:content_for_key)

we get:

{
  :foo => :baz,
  :bar => :qux,
}
2
  • Can you tell how the result is constructed? content_for_key returns nil for anything other than :bar, so what is the logic to build the result? Any time content_for_key returns nil, we map that to :baz? Commented Jun 14, 2018 at 7:57
  • Sorry, my bad, wrote it too fast. I edited my initial code. Commented Jun 14, 2018 at 8:33

2 Answers 2

4

You could use map to convert each element to a [key, value] pair:

array.map { |key| [key, content_for_key(key)] }
#=> [[:foo, :baz], [:bar, :qux]]

followed by to_h to transform the nested array into a hash:

array.map { |key| [key, content_for_key(key)] }.to_h
#=> {:foo=>:baz, :bar=>:qux}

Or you could use each_with_object to populate a hash while traversing the array:

array.each_with_object({}) { |key, hash| hash[key] = content_for_key(key) }
#=> {:foo=>:baz, :bar=>:qux}
Sign up to request clarification or add additional context in comments.

4 Comments

My question is: "Does ruby offer a Array method taking a symbol &:my_func (like mao) and returning an hash with one key per array item and the value of this item would be my_func(item)
@DanielCosta maybe Ruby does have such method and I just prefer posing long-winded solutions instead. But that's rather unlikely ;-)
I actually implemented the .to_h earlier today before posting, was just wondering. Thanks for the answer though
@DanielCosta: no, array doesn't have such method. Nor does anything else. It's just how &:my_func works. It generates a block which, when passed elem, runs elem.my_func. That's it.
1

You could go with something like this. Although it lacks readability in comparison to the answer you already have

array = [:foo, :bar, :mnky]
def content_for_key key
  return :baz if key == :foo
  return :qux if key == :bar
end
array.zip(array.map(&method(:content_for_key))).to_h
#=> {:foo=>:baz, :bar=>:qux, :mnky => nil}

# or 

[array,array.map(&method(:content_for_key))].transpose.to_h
#=> {:foo=>:baz, :bar=>:qux, :mnky=>nil}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.