2

I'm trying to build a items array. I'm looping through a CSV file and when i find matches expanding the list of items. See code below:

items = Array.new
csv.each_with_index do |row,i|
   items << ["a","b","c"].map {|x| row.to_s.gsub(/XXXXXXXXXX/, x.downcase)}
end
puts items.length

This is not returning to desired items array. Am I appended the results of map incorrectly to the array?

2
  • You don't use i in your example. Is it because it's just a simpler example? Commented Jan 14, 2017 at 21:40
  • Show your current result and what you would like to have as a result. Commented Jan 14, 2017 at 22:17

2 Answers 2

6

Yes, you are doing it incorrectly here:

items << ["a","b","c"].map

Items would end up as a nested array. Here's an example of what's happening here:

arr = []
arr << [1].map { |x| x }
arr
# => [[1]]

Instead, you can use +=.

You can also use push if you use the splat operator:

arr = []
arr.push *["a","b","c"].map { |x| x }
arr
# => ["a", "b", "c"]
Sign up to request clarification or add additional context in comments.

3 Comments

perfect! Than you. I didn't know about the * what does that do exactly? I'll accept as soon as the time passes and stackoverflow lets me
it has a few uses, see here. In this case push accepts sequential arguments, so push(:a, :b) == push(*[:a, :b]) == push(*%i{a b}). The last one uses a shorthand to construct an array of symbols.
There's also Array#concat: arr.concat %w[a b c].map { |x| x }
1

As a rule of thumb, if you're :

  • initializing an empty Array
  • iterating over elements, modifiying the array
  • returning the Array at the end

There's a Ruby Enumerable method to help you!

In this case, you could use flat_map and with_index :

csv = %w(1;2;3 4;5;6 7;8;9)

items = csv.flat_map.with_index do |row,i|
   ["a","b","c"].map {|x| row.to_s.gsub(/[159]/, x.downcase)}
end

p items
#=> ["a;2;3", "b;2;3", "c;2;3", "4;a;6", "4;b;6", "4;c;6", "7;8;a", "7;8;b", "7;8;c"]

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.