YAML file do integer calculation

2.6k Views Asked by At

I have a YAML file with the following format

- make: toyota
  group: popular
  cn: FungTin
  en: Toyota
  id: 83
  rank: 2 + %{random_number}
- make: honda
  group: popular
  cn: boontin
  en: Honda
  id: 121
  rank: 3 + %{random_number}

And when I load the file.

MAKE = YAML.load_file("#{Rails.root}/config/data.yml")

I try to do a manipulation by doing:

MAKE['rank'] % {random_number: rand(-1.0..1.0).round(3)}

This results in no implicit conversion of String into Integer error.

How can I achieve that?

2

There are 2 best solutions below

0
On

Your MAKE returning an a array of hash as following, so you should choose an element for perform an operation

MAKE = YAML.load_file("#{Rails.root}/config/data.yml")

=> [{"make"=>"toyota", "group"=>"popular", "cn"=>"FungTin", "en"=>"Toyota", "id"=>83, "rank"=>"2 + %{random_number}"}]

Try this

MAKE.first['rank'] % {random_number: rand(-1.0..1.0).round(3)}
=> "2 + -0.263"

For get summation use eval

eval MAKE.first['rank'] % {random_number: rand(-1.0..1.0).round(3)}
=> 1.737
2
On

We have two ways to do this.
1. If you have only one record, against key, then use following code.

This data is array of hash, So you can get data from first index, like following:

MAKE[0]['rank'] % {random_number: rand(-1.0..1.0).round(3)}

It will return out put like "2 + -0.046"

and if you want to get sum of this, you can do this

eval MAKE[0]['rank'] % {random_number: rand(-1.0..1.0).round(3)}

It will return out put of 1.155

2.In an other case, if you have array of data with same key as in your case, then you have to define, against which make you have to get rank.
Like following code.
I find rank against honda, see following code.

MAKE.select{|x| x['make']=='honda'}[0]['rank'] %{random_number: 5}