简体   繁体   中英

How to read value from a text file in ruby using watir based on position

Can some one please help me write a code in Ruby using Watir so that I can read any value from a given text file based on position and use it as parameter for any field in a web application.

I am new to Ruby and have no idea how to implement this solution.

What I need is, for example, lets say there is a text file called "Test.txt" in d drive main folder. Say it has text like this

13085216660000019999

In the above text I want read the value from position 4 to 8 and ie '8521' and store it as variable and use it in a text field as given below

ie.textField(:name, "de2").set 'Variable got from reading the file'

Something like this ? The [3..6] indicate the 4th position (starting from 0) until the 8th

def my_method var
  puts var
end

File.read("read_var_from_file.txt").each_line{ |line|my_method line[3..6] }

When file contents is

13085216660000019999
13085226660000019999
13085236660000019999

gives as output

8521
8522
8523

EDIT: based on the comment here another version which let you change the begin and end position by line

def read_var file, line_nr, vbegin, vend
    IO.readlines(file)[line_nr][vbegin..vend]
end

puts read_var("read_var_from_file.txt", 0, 1, 3) #line 0, beginning at 1, ending at 3
#=>308

puts read_var("read_var_from_file.txt", 1, 3, 6)

#=>8522

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM