Reputation: 21
file = File.new("pastie.rb", "r")
while (line = file.gets)
labwords = print line.split.first
end
file.close
How do I add spaces between the strings? Right now the output is one giant string. I figure I need to use .join or .inject somehow, but my Ruby syntax skills are poor right now, I am still a beginner. I also need to skip indented spaces in the files paragraph. But I have no clue how to do that.
Upvotes: 0
Views: 4004
Reputation: 2761
You could use strip
to remove all the white space.
file = File.new("pastie.rb", "r")
lines = []
file.each_line do |line|
lines << line.strip.split
end
file.close
puts lines.map { |line| line.join(" ") }.join(" ")
Upvotes: 0
Reputation: 211580
Setting something to the result of a print
is a bit messy. You probably don't mean to do that. Instead, try:
labwords = line.split
print labwords.join(' ')
If you want to skip certain lines, this is the pattern:
while (line = file.gets)
# Skip this line if the first character is a space
next if (line[0,1] == " ")
# ... Rest of code
end
You can also clean up that File.new
call like this:
File.open('pastie.rb', 'r') do |file|
# ... Use file normally
end
That will close it for you automatically.
Upvotes: 5