我有一个我想在Ruby中操作的文件。我相信它应该很容易但是找不到它,因为我是新手。在这些线上我有一些数据,如;
Bassmaster Boats Inc#Bassmaster Boats Inc
Basstream#Basstream
Bat Inflatable Boats#Bat Inflatable Boats
Bavaria Motoryachts#Bavaria Motoryachts
Bavaria Sailing Yachts#Bavaria Sailing Yachts
Bay Craft Inc#Bay Craft Inc
Bay Hawk Industries Inc#Bay Hawk Industries Inc
Bay Quest#Bay Quest
Bay Warrior Boats#Bay Warrior Boats
Bay Water Boats#Bay Water Boats
Bayfield Boat Yard Ltd#Bayfield Boat Yard Ltd
Bayliner Marine Corp#Bayliner Marine Corp
Baymaster Boats Inc#Baymaster Boats Inc
Baymaster by Dargel#Baymaster by Dargel
Bayon#Bayon
Bayrunner#Bayrunner
我想要做的是找到单词之间的空格 - 如果有的话 - 并放置+
并删除#
符号后的任何内容。所以看起来应该是这样的;
Bassmaster+Boats+Inc
Basstream
Bat+Inflatable+Boats
Bavaria+Motoryachts
Bavaria+Sailing+Yachts
.....
.....
.....
提前谢谢
答案 0 :(得分:2)
我建议您使用regular expression查找匹配项。
包含#符号后的字符串
#.*
空间
或
\s
(也与标签字符匹配)
您可以将匹配的字符串替换为gsub!
。
s.gsub!(/#.*/, '').gsub!(/ /, '+')
答案 1 :(得分:1)
执行以下操作:
File.open("another/file", "w") do |file|
File.foreach("filename") do |line|
line[/(#.*)/] = ""
file.puts line.gsub(\s+\, "+")
end
end