Reputation: 99
I get the text containing the sum from an element:
sum = browser.div(:class => 'single sort', :index => 0).div(:class, 'amount').text
Then I have to compare sum
with another integer, but sum
is still a string:
>> sum = browser.div(:class => 'single sort', :index => 0).div(:class, 'amount').text
=> "7 671 \u0420"
>> puts sum.class
String
>> sum.gsub!(/[^0-9]/, '')
=> "7671"
>> puts sum.class
String
>> sum.to_i
=> 7671
>> puts sum.class
String
How can I convert sum
to an integer?
Upvotes: 0
Views: 510
Reputation: 30775
String#to_i
returns a new Object (which is the only sensible implementation; think a moment about what would happen if String#to_i
magically changed the object's class).
So, to assign the integer value to your sum
variable, use
sum = sum.to_i
or (better) introduce a new variable for your integer value:
sum_as_integer = sum.to_i
Upvotes: 2
Reputation: 5197
You have to override the results in this way:
sum = sum.to_i
I suggest to use Integer(sum)
instead of .to_i
method to raise an exception if you try to convert a not number string.
nil.to_i = 0
"".to_i = 0
Integer("")
ArgumentError: invalid value for Integer(): ""
from (irb):1:in `Integer'
from (irb):1
from /Users/nico/.rvm/rubies/ruby-2.2.0/bin/irb:11:in `<main>'
Upvotes: 2