简体   繁体   English

在ruby中传递文件名作为参数

[英]Passing a filename as an argument in ruby

def file_to_array(filename)
  my_text = []
  File.open(filename, "r").each do |line|
    my_text << line
  end
my_text
end

Hello! 你好! My method is supposed to receive a filename when called, open the file and move each line to an array. 我的方法应该在调用时接收文件名,打开文件并将每一行移动到数组。 However, it raises undefined local variable when called and I'm assuming it has something to do with the filename[DOT]ext ?! 但是,它在调用时会引发undefined local variable ,并且我假定它与filename [DOT] ext?!有关。 My call happens in a method below 我的通话发生在以下方法中

def clean_array
  cleaned = file_to_array(text.txt).map do |element|
    element.gsub(/\b['s\!\.\\n]*/m, "")
  end
  cleaned.map! do |el|
    el.split(" ")
    end
  return cleaned.flatten!
  #p cleaned
end

The file name should be a string, and as such, passed in quotes: 文件名应为字符串,并以引号引起来:

file_to_array("text.txt")
# OR
file_to_array('text.txt')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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