rubyarrayschomp

Chomping inside an array


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    |  ********************

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 | **********************