将Ruby字符串转换为哈希表

9
我将配置数据存储在平面文件中编写的哈希中。我想将这些哈希导入到我的类中,以便我可以调用相应的方法。
例子.rb
{ 
  :test1 => { :url => 'http://www.google.com' }, 
  :test2 => {
    { :title => 'This' } => {:failure => 'sendemal'}
  }
}

simpleclass.rb

class Simple
  def initialize(file_name)
    # Parse the hash
    file = File.open(file_name, "r")
    @data = file.read
    file.close
  end

  def print
    @data
  end

a = Simple.new("simpleexample.rb")
b = a.print
puts b.class   # => String

我如何将任何“哈希化”字符串转换为实际哈希?


1
我会将其存储为JSON格式,读取文件并使用JSON.parse函数。 - 23tux
2
使用YML(yaml)或JSON将哈希存储在文件中,并在Ruby文件中读取它作为其实际数据结构。 - Sivalingam
4个回答

13
你可以使用eval(@data),但实际上更好的选择是使用更安全、更简单的数据格式,比如JSON。

4
你可以尝试使用YAML.load方法。
示例:
 YAML.load("{test: 't_value'}")

这将返回以下哈希值。
 {"test"=>"t_value"}

您还可以使用eval方法。

示例:

 eval("{test: 't_value'}")

这也将返回相同的哈希值。
  {"test"=>"t_value"} 

希望这能帮到你。

2
我会使用json gem来完成这个任务。
在你的Gemfile中,你需要使用如下内容:
gem 'json'

然后运行 bundle install

在你的程序中,你需要引入这个宝石(gem)。

require 'json'

然后你可以通过以下方式创建你的 "Hashfield" 字符串:

hash_as_string = hash_object.to_json

并将其写入您的平面文件中。

最后,您可以通过执行以下操作轻松阅读它:

my_hash = JSON.load(File.read('your_flat_file_name'))

这很简单,非常容易做到。


0

如果不清楚,只有哈希值必须包含在JSON文件中。假设该文件名为“simpleexample.json”:

puts File.read("simpleexample.json")
  # #{"test1":{"url":"http://www.google.com"},"test2":{"{:title=>\"This\"}":{"failure":"sendemal"}}}

代码可以在普通的 Ruby 源文件 "simpleclass.rb" 中编写:

puts File.read("simpleclass.rb")
  # class Simple
  #   def initialize(example_file_name)
  #     @data = JSON.parse(File.read(example_file_name))
  #   end
  #   def print
  #     @data
  #   end
  # end

然后我们可以写:

require 'json'
require_relative "simpleclass"

a = Simple.new("simpleexample.json")
  #=> #<Simple:0x007ffd2189bab8 @data={"test1"=>{"url"=>"http://www.google.com"},
  #     "test2"=>{"{:title=>\"This\"}"=>{"failure"=>"sendemal"}}}> 
a.print
  #=> {"test1"=>{"url"=>"http://www.google.com"},
  #    "test2"=>{"{:title=>\"This\"}"=>{"failure"=>"sendemal"}}} 
a.class
  #=> Simple 

构建JSON文件从哈希表中:
h = { :test1=>{ :url=>'http://www.google.com' },
      :test2=>{ { :title=>'This' }=>{:failure=>'sendemal' } } }

我们写:

File.write("simpleexample.json", JSON.generate(h))
  #=> 95 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接