a s.txt file is in the current directory; write a ruby function that reads this file and prints its contents to screen. in ruby

You can use the following Ruby function to read the contents of a file and print them to the screen:

main.rb
def read_file(file_path)
  # Check if the file exists
  if File.exists?(file_path)
    # Open the file in read mode
    file = File.open(file_path, "r")

    # Read the contents of the file
    contents = file.read

    # Print the contents to the screen
    puts contents

    # Close the file
    file.close
  else
    puts "File does not exist."
  end
end
359 chars
19 lines

To use the function, you can call it with the file path as an argument, like this:

main.rb
read_file("s.txt")
19 chars
2 lines

Make sure that the file "s.txt" exists in the current directory. The function will read the content of the file and print it to the screen.

Note: Remember to handle exceptions and errors, such as file not found errors, to ensure your code is robust.

related categories

gistlibby LogSnag