I am a ruby newbie. Want to know how to read a number from a file to a variable. Anyone able to help please? Thanks in advance!
+2
A:
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
yjerem
2009-12-04 04:17:34
A:
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
nas
2009-12-04 05:25:43
Kobojunkie
2009-12-04 22:58:08
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}
nas
2009-12-05 06:41:45