3

environment: ruby1.9.3 , psych(any version) ex:

o = { 'hash' => { 'name' => 'Steve', 'foo' => 'bar' } } 
 => {"hash"=>{"name"=>"Steve", "foo"=>"bar"}} 

#is there a inline option?
puts Psych.dump(o,{:inline =>true})

real result:

---
hash:
  name: Steve
  foo: bar

expect output:

--- 
hash: { name: Steve, foo: bar }
Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
hey mike
  • 2,431
  • 6
  • 24
  • 29
  • I doubt that Psych supports this. The only thing an `ack -i inline` in LibYAML or the Psych sources yields is a parsing test for inline arrays and hashes. Why do you need this? – Niklas B. Mar 04 '12 at 17:30
  • Because my hash is very much like tabular data. I want to see it more clearly and save monitor space. – hey mike Mar 04 '12 at 17:54
  • 1
    I guess you're out of luck then. But you can always write it as CSV or something to a separate file to inspect it. – Niklas B. Mar 04 '12 at 17:55
  • Thanks. Actually I have an object with hierarchical hash and array architecture. I want to dump it into a kind of text format(like YAML). And load it as ruby data later. – hey mike Mar 04 '12 at 17:59
  • 2
    Why not save it as YAML and write a small Ruby script that parses and formats it so you can easily inspect it? This can be done in minutes, if not seconds. – Niklas B. Mar 04 '12 at 18:03
  • @NiklasB : sorry, I am newbie in ruby. Can you give a example code ? thanks you very much. :D – hey mike Mar 05 '12 at 00:57
  • What, for reading YAML and printing the output? If you have problems with that, please create a new question. – Niklas B. Mar 05 '12 at 06:14

2 Answers2

4

Psych supports this, although it isn't at all straightforward.

I've started researching this in my own question on how to dump strings using literal style.

I ended up devising a complete solution for setting various styles for specific objects, including inlining hashes and arrays.

With my script, a solution to your problem would be:

o = { 'hash' => StyledYAML.inline('name' => 'Steve', 'foo' => 'bar') }
StyledYAML.dump o, $stdout
Community
  • 1
  • 1
mislav
  • 14,919
  • 8
  • 47
  • 63
0

The representable gem provides this in a convenient OOP style.

Considering you have a model User:

user.name => "Andrew"
user.age => "over 18"

You'd now define a representer module to render/parse User instances.

require 'representable/yaml'

module UserRepresenter
  include Representable::YAML

  collection :hash, :style => :flow

  def hash
    [name, age]
  end
end

After defining the YAML document you simply extend the user instance and render it.

user.extend(UserRepresenter).to_yaml
#=> ---
hash: [Andrew, over 18]

Hope that helps, Andrew!

apotonick
  • 520
  • 2
  • 9