如何在Rails中使用to_yaml方法,并删除' ---'

时间:2015-09-30 17:07:53

标签: ruby-on-rails ruby-on-rails-4 yaml to-yaml

我试图以yaml格式生成哈希值,但默认情况下,此方法总是在对象前添加---。

> h = {key1: 'v1', key2: 'v2'}
=> {:key1=>"v1", :key2=>"v2"}
> h.deep_stringify_keys.to_yaml
=> "---\n:key1: v1\n:key2: v2\n"

2 个答案:

答案 0 :(得分:3)

蛮力,但它会做到这一点:

json_decode($result, true)

答案 1 :(得分:0)

另一种方法是削减第一行:

IRB:

if settings.DEBUG:
    from django.contrib.staticfiles.urls import staticfiles_urlpatterns
    from django.conf.urls.static import static

    urlpatterns += staticfiles_urlpatterns()
    urlpatterns += static(
        settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

rails console:

>> h = {key1: 'v1', key2: 'v2'}
>> require 'yaml'
>> h.to_yaml
=> "---\n:key1: v1\n:key2: v2\n"
>> h.to_yaml.lines[1..-1].join
=> ":key1: v1\n:key2: v2\n"