0

I want to know how to read a number from a file to a variable. Anyone able to help please?

2 Answers 2

7

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

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)
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}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.