Reputation: 6555
I want to know how to read a number from a file to a variable. Anyone able to help please?
Upvotes: 0
Views: 4833
Reputation: 3696
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
Upvotes: 1
Reputation: 176833
If the entire file's contents is the number, I'd use File::read
to get the contents of the file and String#to_i
to convert the resulting string to an integer.
So:
number = File.read('filename.txt').to_i
Upvotes: 7