Reputation: 173
I have 3 string variables that I need to add. a = "5.21", b= "5.22" and c = "5.23". When I try to add i get a string, I need the numerical value
I have tried the following
a = a.to_f => 5.2
b = b.to_f => 5.2
c = c.to_f => 5.2
sum = a + b + c => 15.6
How do i get output 15.66. please help
Upvotes: 5
Views: 13664
Reputation: 1587
Try taking advantage of Ruby's built in Enumerable
methods. Try this:
a = "5.21"
b = "5.22"
c = "5.23"
[a, b, c].map(&:to_f).inject(:+)
#=> 15.66
Upvotes: 11