0
def read_file_info(*file_name)
  arr = IO.readlines(file_name)
  puts arr
end

read_file_info("abcd.txt")

is giving me an error in

readlines': no implicit conversion of Array into String (TypeError)

2 Answers 2

5

*file_name means variable amount of parameters, you would need to extract the first parameter with file_name[0], check the other answer for single parameter or use multiple files:

def read_file_info(*files)
  files.each do |file_name|
    arr = IO.readlines(file_name)
    puts arr
  end
end

read_file_info("abcd.txt", "efgh.txt")
Sign up to request clarification or add additional context in comments.

Comments

1

Write it as:

def read_file_info(file_name)
  arr = IO.readlines(file_name)
  puts arr
end

read_file_info("abcd.txt")

This is what happened when you pass "abcd.txt" to the method. *file_name creates an array:

def read_file_info(*file_name)
  p file_name
end

read_file_info("abcd.txt")
# >> ["abcd.txt"]

IO.readlines(file_name) expects a single file name as a string, but you gave it an Array, which, in turn, gave you the error:

no implicit conversion of Array into String (TypeError)

If you want to use *file_name then, inside the method, use Array#[] to give your IO.readlines method a single file at a time as a string.

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.