我有一个小的ruby函数来返回一个查询结果我想检查服务器上的env变量,所以我编写了这个函数但它并没有像我期望的那样根据puts输出和代码返回@result我做错什么了?

  def query(params=nil)
    @result = {}
    count = 1
    ENV.each do |k,v|
     @result[count.to_s] = { "name" => k, "company" => v }
     puts "[#{count.to_s}] = { 'name' => #{k}, 'company' => #{v} }"
     count += 1
    end
  end

输出:
irb(main):070:0> query
[1] = { 'name' => ALLUSERSPROFILE, 'company' => C:\ProgramData }
[2] = { 'name' => APPDATA, 'company' => C:\Users\xxxx\AppData\Roaming }
[3] = { 'name' => CLIENTNAME, 'company' => xxxx }
[4] = { 'name' => COLUMNS, 'company' => 160 }
[5] = { 'name' => CommonProgramFiles, 'company' => C:\Program Files (x86)\Common Files }
[6] = { 'name' => CommonProgramFiles(x86), 'company' => C:\Program Files (x86)\Common Files }
[7] = { 'name' => CommonProgramW6432, 'company' => C:\Program Files\Common Files }
....

@结果
irb(main):075:0> @result
=> {"ALLUSERSPROFILE"=>"C:\\ProgramData", "APPDATA"=>"C:\\Users\\xxxx\\AppData\\Roaming", "CLIENTNAME"=>"wxxxx", "COLUMNS"=>"160", "CommonProgramFiles"=>"C:
\\Program Files (x86)\\Common Files", "CommonProgramFiles(x86)"=>"C:\\Program Files (x86)\\Common Files", "CommonProgramW6432"=>"C:\\Program Files\\Common Files .....

最佳答案

嗯,真奇怪。我在本地运行了代码,并按您的预期工作,将@result设置为如下内容…

 > @result
 => {"1"=>{"name"=>"jabjab", "company"=>"jibjib"}, "2"=>{"name"=>"blabla"...

但是,我注意到query返回环境的内容,这就是@result的值的样子。您是否可以按如下方式调用查询,覆盖@result的值这很容易被忽视。
> @result = query

关于ruby - 对环境变量进行索引哈希,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12047443/

10-16 15:09