0

So I am trying to read a file in ruby by giving the name via the command line. So far my code reads as follows:

puts "What is the name of the file to read?"
fileName = gets.chomp

file = $stdin.read.strip
f = File.open(file, “r”)
f.each_line { |line|
    puts line
    }

What I see happening is it is reading the inputs through the command line but does not read a file. For example, I can pass 'input.txt', 'code.txt', and 'sonic.txt' as file names but the program just loops back seeking another input. How can I change this to read the file by name and then out put the contents of that file?

3
  • And removing file = $stdin.read.strip does not yield a quality result. Commented May 17, 2018 at 2:54
  • I can edit the question rather than add comments. Commented May 17, 2018 at 2:55
  • 1
    What is the line fileName = gets.chomp for? fileName is not used anywhere. Commented May 17, 2018 at 2:56

1 Answer 1

2

Your problems are:

  • The line fileName = gets.chomp is useless. Remove that.
  • file = $stdin.read.strip will not let you terminate the input. Use gets to get user's input from the command line.
  • You are using the wrong quotation in your parameter “r” for File.open.
  • You are not closing the file after reading it. It is better to use the block form of File.open to ensure the file is closed after using.

Here is a minimum fix:

puts "What is the name of the file to read?"
file = gets.chomp
File.open(file, "r"){|f|
  f.each_line {|line|
    puts line
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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.