Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.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文件中的哈希集的值_Ruby_File_Hash - Fatal编程技术网

如何打印保存在ruby文件中的哈希集的值

如何打印保存在ruby文件中的哈希集的值,ruby,file,hash,Ruby,File,Hash,我有一个名为ter.txt的文件,其中包含如下哈希集内容: {"qty"=>"gfg", "unit"=>"gfg", "item"=>"xcv", "cost"=>"0.0", "salestax"=>"0.0"} {"qty"=>"gdf", "unit"=>"g", "item"=>"gg", "cost"=>"0.0", "salestax"=>"0.0"} 我想打印哈希集的值。我尝试了以下操作,但出现了未定义局部变量或方法“

我有一个名为ter.txt的文件,其中包含如下哈希集内容:

{"qty"=>"gfg", "unit"=>"gfg", "item"=>"xcv", "cost"=>"0.0", "salestax"=>"0.0"}
{"qty"=>"gdf", "unit"=>"g", "item"=>"gg", "cost"=>"0.0", "salestax"=>"0.0"}
我想打印哈希集的值。我尝试了以下操作,但出现了未定义局部变量或方法“item”的错误


您不应该以这种方式保存数据。这是使用YAML的完美案例。像这样编写文件:

---
- qty: gfg
  unit: gfg
  item: xcv
  cost: 0.0
  salestax: 0.0
- qty: gdf
  unit: g
  item: gg
  cost: 0.0
  salestax: 0.0
然后,您可以加载以下内容:

require 'yaml'
data = YAML.load(File.read 'ter.txt')

我首先将您的数据保存在一个名为test.rb的文件中。我打开文件,读取每一行并将all=>替换为:,使其成为json字符串。然后使用方法将每行json字符串转换为哈希对象。以下是我为解决您的问题而编写的代码:-

require 'json'

File.foreach("#{__dir__}/test.txt") do |line|
  p JSON.parse(line.strip.gsub("=>", ":")).values
end
现在,我从命令提示符下运行代码,并获得您正在查找的输出:-

arup@linux-wzza:~/Ruby> ruby -vw test.rb
ruby 2.0.0p451 (2014-02-24 revision 45167) [i686-linux]
["gfg", "gfg", "xcv", "0.0", "0.0"]
["gdf", "g", "gg", "0.0", "0.0"]
arup@linux-wzza:~/Ruby>

这个问题似乎离题了,因为它显示了对正在解决的问题的最低理解
arup@linux-wzza:~/Ruby> ruby -vw test.rb
ruby 2.0.0p451 (2014-02-24 revision 45167) [i686-linux]
["gfg", "gfg", "xcv", "0.0", "0.0"]
["gdf", "g", "gg", "0.0", "0.0"]
arup@linux-wzza:~/Ruby>