Ruby漂亮打印字符串
我有一个映射,其中键(字符串)可以有非常可变的字符数,我想智能地打印它:Ruby漂亮打印字符串,ruby,logging,printing,Ruby,Logging,Printing,我有一个映射,其中键(字符串)可以有非常可变的字符数,我想智能地打印它: MAP = { "key1" => "value1", "key2" => "value2", } 将打印: key1 -> value1 key2 -> value2 key1 -> value1 key2 -> value2 key3_d
MAP = {
"key1" => "value1",
"key2" => "value2",
}
将打印:
key1 -> value1
key2 -> value2
key1 -> value1
key2 -> value2
key3_dam_it_you_are_a_big_one_indeed -> value3
及
将打印:
key1 -> value1
key2 -> value2
key1 -> value1
key2 -> value2
key3_dam_it_you_are_a_big_one_indeed -> value3
他的想法是key1和key2将根据key3的大小更改它们的打印行
谢谢 怎么样
class Hash
def nice_print
max_key_length = keys.map(&:length).max
each { |key, value| puts "#{key.ljust(max_key_length)} -> #{value}" }
end
end
你打电话
MAP.nice_print
为什么不按你的意愿去做呢?因为每次我想要一辆车的时候,我都不想重新装轮子。这通常是语言内置的类型。那么为什么不使用内置函数呢?这就是问题所在