मैं एक बात लिखा
- स्वचालित रूप से स्तंभ चौड़ाई रिक्तियों के साथ
- रिक्त स्थान का पता लगाता है
सरणियों
[[],[],...]
या हैश की सरणी के
- सरणी
[{},{},...]
कंसोल विंडो
के लिए स्तंभों का बहुत विस्तृत पता नहीं लगाता है सूचियों = [ [123, "SDLKFJSLDKFJSLDKFJLSDKJF"], [123456, "ffff"], ]
array_maxes
def array_maxes(lists)
lists.reduce([]) do |maxes, list|
list.each_with_index do |value, index|
maxes[index] = [(maxes[index] || 0), value.to_s.length].max
end
maxes
end
end
array_maxes(lists)
# => [6, 24]
puts_arrays_columns
def puts_arrays_columns(lists)
maxes = array_maxes(hashes)
lists.each do |list|
list.each_with_index do |value, index|
print " #{value.to_s.rjust(maxes[index])},"
end
puts
end
end
puts_arrays_columns(lists)
# Output:
# 123, SDLKFJSLDKFJSLDKFJLSDKJF,
# 123456, ffff,
और एक अन्य चीज
hashes = [
{ "id" => 123, "name" => "SDLKFJSLDKFJSLDKFJLSDKJF" },
{ "id" => 123456, "name" => "ffff" },
]
hash_maxes
def hash_maxes(hashes)
hashes.reduce({}) do |maxes, hash|
hash.keys.each do |key|
maxes[key] = [(maxes[key] || 0), key.to_s.length].max
maxes[key] = [(maxes[key] || 0), hash[key].to_s.length].max
end
maxes
end
end
hash_maxes(hashes)
# => {"id"=>6, "name"=>24}
puts_hashes_columns
def puts_hashes_columns(hashes)
maxes = hash_maxes(hashes)
return if hashes.empty?
# Headers
hashes.first.each do |key, value|
print " #{key.to_s.rjust(maxes[key])},"
end
puts
hashes.each do |hash|
hash.each do |key, value|
print " #{value.to_s.rjust(maxes[key])},"
end
puts
end
end
puts_hashes_columns(hashes)
# Output:
# id, name,
# 123, SDLKFJSLDKFJSLDKFJLSDKJF,
# 123456, ffff,
संपादित करें: सुधार हैश कुंजी लंबाई में माना जाता है।
hashes = [
{ id: 123, name: "DLKFJSDLKFJSLDKFJSDF", asdfasdf: :a },
{ id: 123456, name: "ffff", asdfasdf: :ab },
]
hash_maxes(hashes)
# => {:id=>6, :name=>20, :asdfasdf=>8}
कॉलम कॉलम को श्वेतसूची में रखना चाहते हैं?
hashes.map{ |h| h.slice(:id, :name) }
# => [
# { id: 123, name: "DLKFJSDLKFJSLDKFJSDF" },
# { id: 123456, name: "ffff" },
#]
एक प्रिंटफ और स्प्रिंटफ है जो एक स्ट्रिंग को प्रारूपित करने के लिए सी तर्कों का उपयोग करता है। वे कर्नल (प्रभावी रूप से अंतर्निर्मित) पर विधियां हैं। Http://www.ruby-doc.org/core/classes/Kernel.html#M005962 देखें। –
printf ("% - 10s% 10s", args) चाल है ... बहुत बहुत धन्यवाद! – predhme
याद रखें [printf (* args)] (http://apidock.com/ruby/Kernel/printf) को एक [स्ट्रिंग # पर कार्यान्वयन] मिला है (http://ruby-doc.org/docs/ProgrammingRuby/html/ ref_c_string.html # स्ट्रिंग._पीसी):%: '"% s% 10s "% [value_name, value] 'बहुत अच्छा लग रहा है। वैसे भी, इस कोड की बड़ी शर्तों के साथ अपने कोड को बर्बाद मत करो! – abstraktor