Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 何时使用Hashie::Mash?_Ruby On Rails_Ruby_Json_Hash - Fatal编程技术网

Ruby on rails 何时使用Hashie::Mash?

Ruby on rails 何时使用Hashie::Mash?,ruby-on-rails,ruby,json,hash,Ruby On Rails,Ruby,Json,Hash,正在从这个JSON API获取一些产品,我想知道——我真的需要Hashie::Mash 实时应用程序: 主控制器.rb: response = prettify(JSON.parse(@json_text)) mashie = Hashie::Mash.new(response) @products = [] mashie.products.each do |product| product.extend Hashie::Extensions::DeepFetch product.p

正在从这个JSON API获取一些产品,我想知道——我真的需要
Hashie::Mash

实时应用程序:

主控制器.rb

response = prettify(JSON.parse(@json_text))
mashie = Hashie::Mash.new(response)

@products = []
mashie.products.each do |product|
  product.extend Hashie::Extensions::DeepFetch

  product.price = product.deep_fetch :sale_price

  @products << product
end
@products

您可能希望执行以下操作:

mashie.products.each do |product|
  product.extend Hashie::Extensions::DeepFetch

  product.price = product.deep_fetch(:sale_price) { 'Not Found' }
  # Returns 'Not Found' if it does not find the key sale_price. It can be anything, like nil, 0, 'Not Found'

  @products << product
end
mashie.products.each do|产品|
product.extend Hashie::Extensions::DeepFetch
product.price=product.deep\u fetch(:sale\u price){“未找到”}
#如果未找到关键销售价格,则返回“未找到”。它可以是任何内容,如nil、0、“未找到”

@所以在这个意义上我可以删除
Hashie::Mash.new(response)
?基本上,我只是尽量简化代码。我不知道为什么我首先需要
Hashie::Mash
(因为我不需要做
product.price?
等)。你不能,因为你需要它来访问像
mashie.products
这样的项目。看起来这是一种在json上迭代产品的好方法。
Hashie::Extensions::DeepFetch::UndefinedPathError in MainController#index
Could not fetch path (sale_price) at sale_price
mashie.products.each do |product|
  product.extend Hashie::Extensions::DeepFetch

  product.price = product.deep_fetch(:sale_price) { 'Not Found' }
  # Returns 'Not Found' if it does not find the key sale_price. It can be anything, like nil, 0, 'Not Found'

  @products << product
end