Kobojunkie
Kobojunkie

Reputation: 6555

Read one number from file into Variable in Ruby

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

Upvotes: 0

Views: 4833

Answers (2)

nas
nas

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

Paige Ruten
Paige Ruten

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

Related Questions