2500mA
2500mA

Reputation: 99

to_i method doesn't convert string

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

Answers (3)

Frank Schmitt
Frank Schmitt

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

NickGnd
NickGnd

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

zwippie
zwippie

Reputation: 15515

You still have to assign the new value to sum:

sum = sum.to_i

Upvotes: 2

Related Questions