【问题标题】:ruby filename path to string errorruby 文件名路径到字符串错误
【发布时间】:2015-10-30 10:35:10
【问题描述】:

这是我的代码:

file = File.open('result.txt', 'w+').read

path = Dir[ENV['HOME'] + '/Desktop/Test/*.txt']

file.puts "this is a #{path} test: "

出现错误:

C:/Users/User/RubymineProjects/Comparison/test.rb:5:in `<top (required)>': private method `puts' called for "":String (NoMethodError)
    from -e:1:in `load'
    from -e:1:in `<main>'

我的预期结果是:

this is a C:/Users/User/Desktop/Test/new_1.txt test: 

我试过这个:

puts "this is a #{path[0]} test: "

这实现了我想要的,但是一旦我这样做file.puts,它就会再次出现同样的错误。

【问题讨论】:

  • 您是要附加到文件还是打印到屏幕上?
  • 我正在尝试将结果放入文件中

标签: ruby filepath


【解决方案1】:

当您在此处执行file.puts 时,您将方法#puts 发送到现在存储在变量file 中的字符串对象。这是因为File#read 方法返回一个字符串。所以,在第一行,fileresult.txt 的内容,然后将其存储在变量中file. Then you're callingputson that string. AndString#puts` 是私有方法,所以不能这样使用你在上面的代码中使用了它。

如果你的意图是写结果this is a C:/Users/User/Desktop/Test/new_1.txt test:,那么你需要这样使用File.open方法:

File.open('result.txt', 'w+') do |file|
  path = Dir[ENV['HOME'] + '/Desktop/Test/*.txt']
  file.puts "this is a #{path} test: "
  # whatever else needs to be written goes here
end

或者,如果您更喜欢命令式而不是块式:

file = File.new('result.txt', 'w+')
# If you prefer `open`, that works too!
# file = File.open('result.txt', 'w+')
path = Dir[ENV['HOME'] + '/Desktop/Test/*.txt']
file.puts "this is a #{path} test: "

# ensure this is closed, or you'll have memory issues if you do this often
file.close 

【讨论】:

  • 谢谢!这现在打印到结果文件中,但它显示为 this is a ["C:/Users/User/Desktop/Test/new_1.txt"] test: 我如何丢失方括号和引号?
  • 当你提到Test/*.txt时,表示它是一个数组,所以这个输出是正确的。但是,如果你想加入数组元素,你可以这样做:"this is a #{path.join(', ')} test: " on the 3rd line
  • 我不想加入他们,我只想输出看起来像this is a C:/Users/User/Desktop/Test/new_1.txt test:,名称根据文件名而变化
猜你喜欢
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-09
  • 1970-01-01
  • 1970-01-01
  • 2015-08-15
  • 2011-11-16
相关资源
最近更新 更多