Best way to pretty print a hash
require 'pp'
pp my_hash
Use pp
if you need a built-in solution and just want reasonable line breaks.
Use awesome_print if you can install a gem. (Depending on your users, you may wish to use the index:false
option to turn off displaying array indices.)
How to pretty print nested dictionaries?
I'm not sure how exactly you want the formatting to look like, but you could start with a function like this:
def pretty(d, indent=0):
for key, value in d.items():
print('\t' * indent + str(key))
if isinstance(value, dict):
pretty(value, indent+1)
else:
print('\t' * (indent+1) + str(value))
More beautiful, indented, pretty-printing
You might want to try the AwesomePrint gem which would return the following by default (the actual output is colored) and is customizable:
aoa = [ [1,2,3], [4,5,6] ]
#=> [
# [0] [
# [0] 1,
# [1] 2,
# [2] 3
# ],
# [1] [
# [0] 4,
# [1] 5,
# [2] 6
# ]
# ]
Parsing a hash to print into a nicely formatted string
You could use the following code:
array = [{"type"=>"work", "value"=>"work@work.com"}, {"type"=>"home", "value"=>"home@home.com"}]
string = array.map do |item|
item = "#{item['type'].capitalize}: #{item['value']}"
end.join(", ")
puts string
Output:
Work: work@work.com, Home: home@home.com, Home: home2@home2.com
How to make Rails.logger.debug print hash more readable
Nevermind, I found the answer to my own question. I need to use
my_hash = {'a' => 'alligator', 'b'=>'baboon'}
Rails.logger.debug "#{my_hash.inspect}"
Then, it looks like
{"b"=>"baboon", "a"=>"aligator"}
How can I print a PowerShell hash object as a hash object?
This ConvertTo-Expression
cmdlet can serialize most (recursive) objects to a PowerShell expression:
$x | ConvertTo-Expression
@{
'c' = @{'foo' = 'bar'}
'b' = 2
'a' = 1
}
Related Topics
How to Convert a Ruby Object to JSON
What Is '-Mix' in a Ruby Regular Expression
How to Create a Hash in Ruby That Compares Strings, Ignoring Case
To_Specs': Could Not Find Chef (>= 0) Amongst [] (Gem::Loaderror)
Calling Sinatra from Within Sinatra
Ruby Block to String Instead of Executing
How to Create a Nokogiri Case Insensitive Xpath Selector
Why Is Enumerable#Each_With_Object Deprecated
How to Use a Variable as Object Attribute in Rails
Does Ruby Call Initialize Method Automatically
How to Pass Data from a Controller to a Model with Ruby on Rails
Devise Login with User or Admin Models and Basecamp Style Subdomains
Yaml Indentation for Array in Hash
The Compiler Failed to Generate an Executable File. (Runtimeerror)
In Ruby, Is There No Way to Dynamically Define a Local Variable in the Current Context