English 中文(简体)
变幻剂
原标题:Variables magic and read from file
  • 时间:2009-10-16 11:34:41
  •  标签:

Assume, i got the following file (input.txt):

name = "Peter"
age = 26
family_status = married

所提及的线路可按随机顺序储存,代号为:

family_status = married
name = "Peter"
age = 26

在我的节目中,我还有各种变量:family_status,age。 在一个周期中,我是如何从档案中读到这些线的,并且将变数与数值对应的?

最佳回答

Setting Variables

这取决于几个事实。

  • What kind of variables do you have (local variables, instance variables, class variables, or global variables)
  • What kind of type is family_status (String, Symbol, whatever)

我假定,你正在使用实例变数。

def read_vars(io, vars)
  io.each do |line|
    # ensure the line has the right format (name = var)
    raise "wrong format" unless line=~ /^s*(w+)s*=s*"?(.*?)"?s+$/
    var= :"@#{$1}"
    # pick the type of the data
    value= case vars[var]
    when String
      $2
    when Integer
      $2.to_i
    when Symbol
      $2.to_sym
    else
      raise "invalid var"
    end
    instance_variable_set(var, value)
  end
end

read_vars(File.read("input.txt", :@age => Integer, :@name => String, :@family_status => Symbol )

如果您不使用实例变量,那么你必须修改<代码>instacne_variable_set和var=:”@,以适应你们的需要。 该法典具有以下优势:

  • You control which variables can be set
  • You control which types these variables have
  • You can easily add new variables and/or change types of variables without changing the read code
  • You can use this code to read entirely different files, without writing new code for it

reading as YAML

如果你们的需要与你的问题不一样具体,我会采取完全不同的做法。

我将把<代码>输入.txt作为Yaml文档。 在Myaml syntax中,它希望:

---
name: Peter
age: 26
family_status: :married

你可以读到:

YAML.load(File.read("input.txt")) # => {"name" => "Peter", "age" => 26, "family_status" => :married }

如果你不控制<条码>输入.txt文档,你不控制哪类数据。 我将用<条码>输入.yaml代替<条码>输入.txt。 如果你想要了解更多情况,那么如何撰写亚穆利亚尔案卷,请查阅:http://yaml.kwiki.org/?YamlInFiveMinutes。 http://www.ruby-doc.org http://www.ruby-doc.org/stdlib/libdoc/yaml/rdoc/index.html

问题回答

假设档案确实像你那样是正常的,你可以把所有东西都lu成像:

input = IO.read("input.txt")
input_hash = Hash[*input.gsub(/"/,"").split(/s*[
=]s*/)]

这使你:

=> {"name"=>"Peter", "family_status"=>"married", "age"=>"26"}

但随后,你真的需要制定某些可变的特例,来做你想要的任何类型的处理,特别是对于任何家庭来说,情况是......。

你可以尝试这样做。 并非一行:

class Test
  attr_accessor :name, :age, :family_status

  def load
    File.foreach( input.txt ) do |line|
      match = line.match /^(S+)s*=s*"?(S+?)"?s*$/
      self.send("#{match[1]}=", match[2]) if match
    end
  end
end

test = Test.new
test.load




相关问题