2

I have small ruby function to return a query result. I want to check the env variables on my server so i wrote this function. But it's not returning @result as I expected based on the puts output and the code. What am I doing wrong?

  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

Puts output:

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 }
....

@result

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 .....
Martlark
  • 14,208
  • 13
  • 83
  • 99

2 Answers2

1

use array for lists:

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

@result = query

and then print it as you want.

if you really want indexed hash, use:

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

Hmm, that's strange. I ran the code locally and it works as you expect it to, setting @result to something like the following...

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

However, I did notice that query returns the contents of environment, which is what the value of @result looks like. Is it possible that you are calling query as follow, overwriting the value of @result? This could be easily overlooked.

> @result = query
Blake Taylor
  • 9,217
  • 5
  • 38
  • 41