Make all arrays of hash to have same size

Hello to all,

First post in Ruby-Forum. Maybe some Ruby expert could help me.

Does somebody knows how to make all arrays of a hash to have the same
size?
This is, add blank elements to smaller arrays.

I found that for an array of arrays this could be done like this:

array=[[“x”,“y”,“z”], [“w”,“p”], [“q”, “x”, “c”, “v”]]
max_size = array.map(&:size).max
array.map { |a| Array.new(max_size) { |i| a[i] || ‘’ } }

Output: [[“x”, “y”, “z”, “”], [“w”, “p”, “”, “”], [“q”, “x”, “c”,“v”]]

For an hash of arrays I’ve been trying to replicate the code above
without succes.

hash = {“1”=>[“x”,“y”,“z”], “2”=>[“w”,“p”], “3”=>[“q”, “x”, “c”, “v”]}
max_size = hash.values.map(&:size).max
myHash.values.map { |k,v| myHash.new(max_size) { |i| a[i] || ‘’ } }

Asked here too
http://forums.devshed.com/ruby-programming-142/arrays-size-adding-blanks-hash-arrays-961236.html

Thanks in advance.

Von Levix wrote in post #1144459:

Does somebody knows how to make all arrays of a hash to have the same
size?
This is, add blank elements to smaller arrays.

I found that for an array of arrays this could be done like this:

array=[[“x”,“y”,“z”], [“w”,“p”], [“q”, “x”, “c”, “v”]]
max_size = array.map(&:size).max
array.map { |a| Array.new(max_size) { |i| a[i] || ‘’ } }

You are not changing array here. Instead you are creating a copy of all
the Arrays.

Output: [[“x”, “y”, “z”, “”], [“w”, “p”, “”, “”], [“q”, “x”, “c”,“v”]]

For an hash of arrays I’ve been trying to replicate the code above
without succes.

hash = {“1”=>[“x”,“y”,“z”], “2”=>[“w”,“p”], “3”=>[“q”, “x”, “c”, “v”]}
max_size = hash.values.map(&:size).max
myHash.values.map { |k,v| myHash.new(max_size) { |i| a[i] || ‘’ } }

Again, you are not modifying the Hash but you are copying the values
Array which in itself is a copy already. Plus, it is totally unclear
what myHash.new is supposed to do.

Asked here too

http://forums.devshed.com/ruby-programming-142/arrays-size-adding-blanks-hash-arrays-961236.html

Why?

irb(main):004:0> hash = {“1”=>[“x”,“y”,“z”], “2”=>[“w”,“p”], “3”=>[“q”,
“x”, “c”, “v”]}
=> {“1”=>[“x”, “y”, “z”], “2”=>[“w”, “p”], “3”=>[“q”, “x”, “c”, “v”]}
irb(main):005:0> max = hash.values.inject(0){|m, a| a.size > m ? a.size
: m}
=> 4
irb(main):006:0> hash.values.each {|a| a << ‘’ while a.size < max}
=> [[“x”, “y”, “z”, “”], [“w”, “p”, “”, “”], [“q”, “x”, “c”, “v”]]
irb(main):007:0> hash
=> {“1”=>[“x”, “y”, “z”, “”], “2”=>[“w”, “p”, “”, “”], “3”=>[“q”, “x”,
“c”, “v”]}

Hello Robert,

Many thanks for your help.

It works fine the same solution for array or hash. And I asked before in
other forum and asked here after any answer in the other forum.

Thanks again.

Best regards

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs