anonimo342
anonimo342

Reputation: 73

how convert string to int in ruby

I obtain a string after use number = sep[1].scan(/\w+/) but later I need to compare number with other number. I known when I use sep[1].scan(/\w+/) I discard other symbols but how convert my string number into a real integer?

Upvotes: 4

Views: 2443

Answers (3)

sbagdat
sbagdat

Reputation: 850

If you are sure it is a valid number, you can use Kernel#Integer method. Otherwise it will raise an ArgumentError.

Integer("123")  # 123
Integer("123xyz")  # `Integer': invalid value for Integer(): "123xyz" (ArgumentError)

Upvotes: 0

user15181765
user15181765

Reputation:

The code you have written just captures a whole word which is equivalent to [a-zA-Z0-9_] any number of times.

string.scan(/\w+/) will scan for that word. But if you want to just extract numbers from the words, just use string.scan(/\d+/) and then convert using .to_i. If you scan using \w+ and then if you call .to_i, two things can happen

Case 1: string starting with a number

In this case, for example "879random" will return 879 when .to_i is called over it. The .to_i method looks for numbers from the starting of the string. It doesn't capture randomly scattered numbers in a string. If the starting is not a number look at case 2.

Case 2: string not starting with a number

In this case, it will always return 0 no matter what your string is if it starts with a non-digit. For example, "s729742384023041646891273948" will return 0. The method .to_i starts grouping digits from the start of the string until it finds a non-digit or till the end.

So it is better to use .scan(/\d+/) rather than .scan(/\w+/)

Upvotes: 1

anonimo342
anonimo342

Reputation: 73

The solution for this problem is: with regular expression; number is an array with length 1 so I need to convert number[0] to array, like this: num_integer =number[0].to_i

Upvotes: 3

Related Questions