Question

puts (Array.new(200) {(1..100).to_a[rand(100)]}).group_by { |x| (x - 1) / 10 }.sort_by { |x| x }.map {|x, y| [10 * x + 1, "-" , 10 * (x + 1), "   ", "|", "  ", "*" * (y.length)]}

In the above code, I need to chomp after each comma in the map block. The issue is that I keep getting the following output no matter what I do:

1
-
10

|

*************************

How can I chomp inside the map to make it look like the following

1-10    |  ********************
Was it helpful?

Solution

(Array.new(200) {(1..100).to_a[rand(100)]}).group_by { |x| (x - 1) / 10 }.sort_by { |x| x }.map {|x, y| [10 * x + 1, "-" , 10 * (x + 1), "   ", "|", "  ", "*" * (y.length)]}.collect { |a| a.join }.each { |a| puts a }

But if your goal is to do that, why are you creating the nested arrays in the first place?

a = Array.new(200) {(1..100).to_a[rand(100)]}
a = a.group_by { |x| (x - 1) / 10 }
a = a.sort_by { |x| x }
a = a.map { |x, y| "#{10 * x + 1} - {#10 * (x + 1)}   |  #{'*' * (y.length)}" }
a.each { |bag| puts bag }

With some cleanup, maintaining your single-line thing:

Array.new(200) { rand(100) + 1 }.group_by { |x| (x - 1) / 10 }.sort.map { |x, y| sprintf "%2d - %3d | %s" % [10 * x + 1, 10 * (x + 1), '*' * y.length] }.each { |l| puts l }

 1 -  10 | ********************
11 -  20 | *******************
21 -  30 | *************************
31 -  40 | ***********************
41 -  50 | ****************
51 -  60 | *******************
61 -  70 | *****************
71 -  80 | ****************
81 -  90 | ***********************
91 - 100 | **********************

OTHER TIPS

You could not create a array at the end but just a string ?

puts (Array.new(40) {(1..20).to_a[rand(20)]}).group_by { |x| (x - 1) / 10 }.sort_by { |x| x }.map {|x, y| %Q!#{10 * x + 1} - #{10 * (x + 1)}  |  #{"*" * (y.length)}!}
puts (Array.new(200) {(1..100).to_a[rand(100)]}).group_by { |x| (x - 1) / 10 }.sort.map{|x,y| "#{x*10+1}-#{10*(x+1)} | #{'*'*y.size}" }

btw, it's not necessary to use .sort_by { |x| x } when you do not use any specific options, simply .sort is enough in your case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top