I want to know how to read a number from a file to a variable. Anyone able to help please?
2 Answers
If your file has a string or variable length of characters that has some numbers in it then you can get all the numbers using regex and assign it to your variable e.g.
file_contents = File.read('filename') # => "a string of character with 23 number and 123 in it"
numbers = file_contents.scan(/\d+/) # => ['23', '123']
To convert the above array of string numbers to integer
numbers.collect! &:to_i # => [23, 123]
Then you can assign these number to any variable you want
number1 = numbers.first
number2 = numbers.last
2 Comments
Kobojunkie
I tried the code you posted above and come up with some errors on my end. the line numbers.collect! &:to_i gives the error wrong argument type Symbol (expected Proc) (TypeError)
nas
this symbol to_proc is added in ruby 1.8.7 so probably you are running ruby 1.8.6. Try this code then numbers.collect!{|num| num.to_i}