简体   繁体   中英

How to push key and value to an empty hash with a loop in Ruby on rails

I want to use Bing search results for my webpage. To use their json data I found this solution:

new_bing_results = bing_results[0][:Web]


result = { }


result[:title] = new_bing_results[0][:Title]
result[:description] = new_bing_results[0][:Description]
result[:url] = new_bing_results[0][:Url]
result[:display_url] = new_bing_results[0][:DisplayUrl]

result[:title1] = new_bing_results [1][:Title]
result[:description1] = new_bing_results [1][:Description]
result[:url1] = new_bing_results [1][:Url]
result[:display_url1] = new_bing_results [1][:DisplayUrl]

result[:title2] = new_bing_results [2][:Title]
result[:description2] = new_bing_results [2][:Description]
result[:url2] = new_bing_results [2][:Url]
result[:display_url2] = new_bing_results [2][:DisplayUrl]

....

          result

How can I create a loop that is doing the same thing 50 times without having to repeat the same code.

I tried this but only get errors:

new_bing_results = bing_results[0][:Web]
$i = 0
$num = 50
result2 = {}

while $i < $num do
    result[:title$i]  = new_bing_results[$i][:Title]

......

end

result

The problem is that I do not find a solution for adding my $i number to the key result[:title] as in the value new_bing_results[$i][:Title]

This should do the trick

result = {}
50.times do |i|
  result["title#{i}".to_sym] = new_bing_results[i][:Title]
  result["description#{i}".to_sym] = new_bing_results[i][:Description]
  result["url#{i}".to_sym] = new_bing_results[i][:Url]
  result["display_url#{i}".to_sym] = new_bing_results[i][:DisplayUrl]
end

50.times will run from 0 to 49 and you can use interpolation to avoid the repetition.

You can use .to_sym method. For example:

new_bing_results =  [{Title: "Title"}]
result = {}
result["title#{i}".to_sym] = new_bing_results[i][:Title]
result
=> {:title0=>"Title"}

You can use string interpolation and then the to_sym method.

    result = {}
    50.times do |n|
      result["title#{n}".to_sym] = new_bing_results[n][:Title]
    end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM