
February 21st, 2011, 07:44 PM
|
|
Contributing User
|
|
Join Date: Jan 2004
Location: Constant Limbo
|
|
The following code will accept the hash and format it into strings of key/value pairs (joined with '=') and print out to a particular width. The width will be exceeded it the key/value pair is greater than the overall width and the the '=' are not aligned. You can work that in if you'd like. Below are sample runs.
Code:
ruby
def format(hsh,width=80)
used = 0
hsh.collect { |k,v| [k,v].join "=" }.each do |str|
if used > 0 and used + str.size >= width
puts
used = 0
end
print "#{str} "
used += str.size + 1
end
puts
end
Code:
# format h
yetmore=yousay somekey=somevalue 1=2 3=45500034 anotherkey=anothervalue
332435=1123243
Code:
# format h, 20
yetmore=yousay
somekey=somevalue
1=2 3=45500034
anotherkey=anothervalue
332435=1123243
|