lulalala
lulalala

Reputation: 17981

Ruby array to hash: each element the key and derive value from it

I have an array of strings, and want to make a hash out of it. Each element of the array will be the key, and I want to make the value being computed from that key. Is there a Ruby way of doing this?

For example:

['a','b'] to convert to {'a'=>'A','b'=>'B'}

Upvotes: 30

Views: 35655

Answers (9)

aidan
aidan

Reputation: 9576

Ruby's each_with_object method is a neat way of doing what you want

['a', 'b'].each_with_object({}) { |k, h| h[k] = k.upcase }

Upvotes: 9

philipjkim
philipjkim

Reputation: 4139

From Rails 6.x, you can use Enumerable#index_with:

irb(main):002:0> ['a', 'b'].index_with { |s| s.upcase }
=> {"a"=>"A", "b"=>"B"}

Upvotes: 8

Joshua Pinter
Joshua Pinter

Reputation: 47531

Pass a block to .to_h

[ 'a', 'b' ].to_h{ |element| [ element, element.upcase ] }
#=> {"a"=>"A", "b"=>"B"}

Thanks to @SMAG for the refactor suggestion!

Upvotes: 5

Mark Thomas
Mark Thomas

Reputation: 37517

Here's another way:

a.zip(a.map(&:upcase)).to_h

#=>{"a"=>"A", "b"=>"B"}

Upvotes: 6

Ismael
Ismael

Reputation: 16730

Not sure if this is the real Ruby way but should be close enough:

hash = {}
['a', 'b'].each do |x|
  hash[x] = x.upcase
end

p hash  # prints {"a"=>"A", "b"=>"B"}

As a function we would have this:

def theFunk(array)
  hash = {}
  array.each do |x|
    hash[x] = x.upcase
  end
  hash
end


p theFunk ['a', 'b', 'c']  # prints {"a"=>"A", "b"=>"B", "c"=>"C"}

Upvotes: 1

Jens Tinfors
Jens Tinfors

Reputation: 880

Here's a naive and simple solution that converts the current character to a symbol to be used as the key. And just for fun it capitalizes the value. :)

h = Hash.new
['a', 'b'].each {|a| h[a.to_sym] = a.upcase}
puts h

# => {:a=>"A", :b=>"B"}

Upvotes: 4

brad
brad

Reputation: 32355

%w{a b c}.reduce({}){|a,v| a[v] = v.upcase; a}

Upvotes: 22

Ricardo Acras
Ricardo Acras

Reputation: 36244

You can:

a = ['a', 'b']
Hash[a.map {|v| [v,v.upcase]}]

Upvotes: 56

Kassym Dorsel
Kassym Dorsel

Reputation: 4843

Which ever way you look at it you will need to iterate the initial array. Here's another way :

a = ['a', 'b', 'c']
h = Hash[a.collect {|v| [v, v.upcase]}]
#=> {"a"=>"A", "b"=>"B", "c"=>"C"}

Upvotes: 5

Related Questions