Home > OS >  Ruby // Selecting and Transferring items from hashes using Input
Ruby // Selecting and Transferring items from hashes using Input

Time:11-09

I am making a basic CLI web scrapper using Ruby. The user will be asked which stock index they would like to see. Their input will be taken as:

$input = gets.chomp.downcase.to_s

I have a hash that I am using as a makeshift database. Not the best practice, I know, but it's the best thing I have come up with only using Ruby objects.

Example hash:

index_info_resource = {
   "dax" => {
      full_name:  "Deutscher Aktienindex (German stock index)",
      exchange:   "Frankfurt Stock Exchange"
      web_site:   "investing.com/dax/test
   },
   "fchi" => {
      full_name:  "Cotation Assistée en Continu",
      exchange:   "Euronext Paris"
      web_site:   "investing.com/fchi/test
   }
}

Because there will be a scrapper class, information will coming from there as well as from this db hash, I was thinking to make a staging hash: @@requested_index = Hash.new where I would then add the information I need like so:

@@requested_index[:full_name] = index_info_resource["#{"dax"}"][:full_name]

My problem is when I use the users input in this way:

@@requested_index[:exchange] = index_info_resource["#{"$input"}"][:full_name]

I get this error:

undefined method `[]' for nil:NilClass (NoMethodError)

I am not sure why or how to fix this. If I use just an identical string, it works. If the user's input is that same string, it does not.

Thank you for you time.

CodePudding user response:

Your $input is already a string therefore you do not need string interpolation in this case. Additionally "#{"$input"}" will evaluate to "$input" not the value of that variable.

Just change

@@requested_index[:exchange] = index_info_resource["#{"$input"}"][:full_name]

to

@@requested_index[:exchange] = index_info_resource[$input][:full_name]
  • Related