Rafeh Ishtiaq
Rafeh Ishtiaq

Reputation: 113

Combining symbols in ruby

I have two arrays, one with symbols and another with strings.

a = [:man, :woman]
b = ["one", "two"]

I'm trying to combine every symbol with each string in the array so that the output would be:

[:man_one, :man_two, :woman_one, :woman_two]

I've tried

b = b.to_s
q = []
a.each do |n|
  q.push (n.to_s + b.each {|w| "_" + w}).to_sym
end
p q

But this gives me an error. How can I create the new symbols?

Upvotes: 3

Views: 2529

Answers (5)

iGian
iGian

Reputation: 11183

Just to give another example of https://ruby-doc.org/core-2.5.3/Array.html#method-i-product, passing a block:

res = []
a.product(b){ |e| res << e.join('_').to_sym }
res #=> [:man_one, :man_two, :woman_one, :woman_two]

Upvotes: 0

Jay Dorsey
Jay Dorsey

Reputation: 3662

Look at Array#product

a = [:man, :woman]
b = ["one", "two"]
a.product(b).map { |arr| arr.join('_') }.map(&:to_sym)

Your error is because you're trying to call each on a String (b), because you converted it with to_s a few lines up.

If you want to do this with the temporary variable, q, you can write it like this:

a=[:man, :woman ]
b=["one", "two"]
q=[]

a.each do |tmp_a|
  b.each do |tmp_b|
    q.push((tmp_a.to_s + '_' + tmp_b).to_sym)
  end
end

puts q

Upvotes: 0

sawa
sawa

Reputation: 168071

A straightforward way is this:

a.product(b).map{|arr| arr.join("_").to_sym}
#=> [:man_one, :man_two, :woman_one, :woman_two]

Upvotes: 4

Gregory Ostermayr
Gregory Ostermayr

Reputation: 1121

Yet another riff on the nested loop without mutating an external variable within the loops

a = [:man, :woman]
b = ["one", "two"]

q = a.flat_map do |n|
  b.map do |w|
    "#{n}_#{w}".to_sym
  end
end

p q 

Upvotes: 0

Sebasti&#225;n Palma
Sebasti&#225;n Palma

Reputation: 33420

You have some problems while trying to achieve your expected output:

Converting b to String gives you nothing else than "[\"one\", \"two\"]", which isn't iterable, so I guess that mess everything.

In the other hand it seems you're trying to iterate on a, to iterate on b then, but pushing to q right the value of the elements of a to String plus a call on each to b, seems to give you nothing.

With a slight tweak you can make that work:

a = [:man, :woman]
b = ["one", "two"]
q = []

a.each do |n|
    b.each do |w|
        q << ("#{n}_#{w}").to_sym
    end
end

p q
# [:man_one, :man_two, :woman_one, :woman_two]

Upvotes: 2

Related Questions