Jon Kim wrote:
Hi,
I am newbie in Ruby. I have a question about indenting string.
there is strings like below:
www.google.com => 123.123.123.12
www.ibm.com => 123.112.123.12
www.iowahawkeyes => 123.123.112.12
i want to make above like next
www.google.com => 123.123.123.12
www.ibm.com => 123.112.123.12
www.iowahawkeyes => 123.123.112.12
original code was
puts (dns + " => " + ip)
I tried next code
puts (dns + " "*(20 - dns.length) + " = > " + ip)
but it did not work well. please teach me how to do it.
You could do
puts "#{dns.ljust(20)} => #{ip}"
-Justin
OK, I'm going to go out on a limb and presume that you obtain the successive dns and ip values from some sort of data structure. I'm going to further assume a hash since you're using the association syntax in your output string, but feel free to generalize the parts of this code that handle that iteration.
my_data = {
?> 'www.google.com' => '216.68.119.70',
?> 'www.ibm.com' => '129.42.60.216',
?> 'www.iowahawkeyes.com' => '199.108.163.135',
?> }
=> {"www.google.com"=>"216.68.119.70", "www.ibm.com"=>"129.42.60.216", "www.iowahawkeyes.com"=>"199.108.163.135"}
width = my_data.keys.inject(0) {|wmax,dns| [dns.length, wmax].max }
=> 20
my_data.each do |dns,ip|
?> puts "%-*s => %s"%[width, dns, ip]
end
www.google.com => 216.68.119.70
www.ibm.com => 129.42.60.216
www.iowahawkeyes.com => 199.108.163.135
=> {"www.google.com"=>"216.68.119.70", "www.ibm.com"=>"129.42.60.216", "www.iowahawkeyes.com"=>"199.108.163.135"}
?> my_data['www.letmegooglethatforyou.com'] = '209.20.88.2'
=> "209.20.88.2"
?> width = my_data.keys.inject(0) {|wmax,dns| [dns.length, wmax].max }
=> 29
my_data.each do |dns,ip|
?> puts "#{dns.ljust(width)} => #{ip}"
end
www.google.com => 216.68.119.70
www.ibm.com => 129.42.60.216
www.letmegooglethatforyou.com => 209.20.88.2
www.iowahawkeyes.com => 199.108.163.135
=> {"www.google.com"=>"216.68.119.70", "www.ibm.com"=>"129.42.60.216", "www.letmegooglethatforyou.com"=>"209.20.88.2", "www.iowahawkeyes.com"=>"199.108.163.135"}
You could also put a limit on the width of the column so that one long value doesn't "win" or analyze the widths for some other property (like rounding up to a multiple of 4 or something).
-Rob
Rob Biedenharn http://agileconsultingllc.com
Rob@AgileConsultingLLC.com
···
On Dec 8, 2009, at 5:11 AM, Justin Collins wrote: