ruby - 制作环境变量的索引哈希

标签 ruby rhomobile

我有一个小的 ruby​​ 函数来返回查询结果。我想检查服务器上的环境变量,所以我编写了这个函数。但它并没有像我预期的那样根据 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 .....

最佳答案

对列表使用数组:

def query
  ENV.map {|k,v|  { "name" => k, "company" => v } }
end

@result = query

然后根据需要打印。

如果你真的想要索引哈希,使用:

def query
  result = []
  ENV.each_with_index {|v,i|  result.push(i, { "name" => v[0], "company" => v[1] }) }
  Hash[*result]
end

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

相关文章:

ruby - 使用 Ruby OpenSSL 下载和读取证书

ruby - 编写无损移位的最紧凑方式

Ruby open-uri 无法打开 url (m1 mac)

ruby-on-rails - "bundle install"从 Rails 控制台系统命令发出时未创建 Gemfile.lock

iphone - RhoStudio 未内置于 XCode - Curl

ruby - ruby 模块有构造函数吗?

iphone - 有人用过 rhomobile 框架吗?

redis - Rhomobile rake redis 中止

android - Rhomobile 与 Phonegap 的注意事项