Goose Looking
Goose Looking

Reputation: 23

Ruby: open textfile and take lines as string arguments

Here is my Code:

if ARGV.length != 1
    puts "We need exactly one parameter. The name of a file."
    exit;
end

filename = ARGV[0]
puts "Going to open '#{filename}'"

fh = open filename

fh.each do |line|
    HID_num(line)
end

fh.close
def HID_num(str)
    temp = str.split(" ")
    temp.map do |element|
        matches = element.match(/\A[A-Z]{4}(\d{8})\z/)
        next unless matches
        matches[1]
    end.compact
end

So my issue here is that I need to open any textfile.txt and go to the terminal call ruby example.rb textfile.txt It should print the valid strings only.

My issue is I cannot seem to make it work. Could anyone help out?

Upvotes: 2

Views: 53

Answers (1)

Kavitha
Kavitha

Reputation: 310

You are really close.

First, you have forgotten the puts method while invoking HID_num, to print the output.

Next, define the method before invoking it. The Ruby in default flavour is interpreted. Else you run into the NoMethodError.

Finally, to get the actual matched substrings alone to be printed, try map! instead of map method. It overwrites the array of original strings with the matched substring, thereby retaining the matches.

    temp.map! do |element|
        matches = element.match(/\A[A-Z]{4}(\d{8})\z/)
        next unless matches
        matches[1]
    end.compact

Upvotes: 1

Related Questions