gpt4 book ai didi

ruby-on-rails - 如何将 ruby​​ 哈希对象转换为 JSON?

转载 作者:bug小助手 更新时间:2023-10-28 01:25:56 37 4
gpt4 key购买 nike

如何将 ruby​​ 哈希对象转换为 JSON?所以我在下面尝试这个例子,它不起作用?

我正在查看 RubyDoc,显然 Hash 对象没有 to_json 方法。但我在博客上看到 Rails 支持 active_record.to_json 并且还支持 hash#to_json。我可以理解 ActiveRecord 是一个 Rails 对象,但 Hash 不是 Rails 原生的,它是一个纯 Ruby 对象。所以在 Rails 中你可以做 hash.to_json,但在纯 Ruby 中不行??

car = {:make => "bmw", :year => "2003"}
car.to_json

最佳答案

Ruby 的众多优点之一是可以使用您自己的方法扩展现有类。这就是所谓的“类(class)重新开放”或猴子修补(不过是后者 can vary 的含义)。

所以,看这里:

car = {:make => "bmw", :year => "2003"}
# => {:make=>"bmw", :year=>"2003"}
car.to_json
# NoMethodError: undefined method `to_json' for {:make=>"bmw", :year=>"2003"}:Hash
# from (irb):11
# from /usr/bin/irb:12:in `<main>'
require 'json'
# => true
car.to_json
# => "{"make":"bmw","year":"2003"}"

如你所见,要求 json 神奇地将方法 to_json 引入了我们的 Hash

关于ruby-on-rails - 如何将 ruby​​ 哈希对象转换为 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3183786/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com