How to pad a string with spaces in Ruby? - Printable Version +- 0Day Forums (https://zeroday.vip) +-- Forum: Coding (https://zeroday.vip/Forum-Coding) +--- Forum: Ruby (https://zeroday.vip/Forum-Ruby) +--- Thread: How to pad a string with spaces in Ruby? (/Thread-How-to-pad-a-string-with-spaces-in-Ruby) |
How to pad a string with spaces in Ruby? - alanealanine424 - 07-19-2023 Is there a Ruby function that can pad a string? Original `[477, 4770]` Expected `["477 ", "4770 "]` RE: How to pad a string with spaces in Ruby? - milarite461519 - 07-19-2023 You should use [`String#ljust`]( [To see links please register here] ) from Ruby standard library:arr = [477, 4770] strings = arr.map { |number| number.to_s.ljust(5) } # => ["477 ", "4770 "] RE: How to pad a string with spaces in Ruby? - cindiwppy - 07-19-2023 arr = [477, 4770] arr.collect {|num| num.to_s.ljust(5)} RE: How to pad a string with spaces in Ruby? - abrachia123952 - 07-19-2023 You can use printf formatting from [Kernel]( [To see links please register here] ) as well :arr = [477, 4770] arr.map { |i| "%-5d" % i } RE: How to pad a string with spaces in Ruby? - ginoxwhvbmwge - 07-19-2023 You need the method [String#ljust][1]. Here is an example: t = 123 s = t.to_s.ljust(5, ' ') Please note that `' '` is the default padding symbol. I only added it for clarity. [1]: [To see links please register here] |