Reputation: 2985
I want to reverse the words of a text file:
If my input is:
Hello World
My output should be:
World Hello
I tried this:
File.open('teste.txt').each_line do |line|
print line.reverse.gsub(/\n/,"")
end
but I got the characters reversed.
Upvotes: 0
Views: 3318
Reputation: 525
Split the string on spaces, reverse it, then join them together.
You could make a method to do it as such:
def reverse_words(string)
return string.split(" ").reverse.join(" ")
end
then later, call that method with:
print reverse_words("Hello World")
Or set a string to the returned value:
reversed_string = reverseWords("Hello World")
Upvotes: 0
Reputation: 6310
"Hello World".split.reverse.join(" ")
=> "World Hello"
It splits the string into an array with a whitespace being the default delimiter. Then it reverses the array and concatenates the strings in the array using a white space as well.
Your solution should look like this:
File.open("test.txt").each_line do |line|
puts line.split.reverse.join(" ")
end
puts
appends a linebreak after the output, while print
does not. This is neccessary, because split
discards the original linebreak on each line, when splitting it into an array of words.
Upvotes: 10
Reputation: 230336
Break string into words and reverse that.
"Hello World".split.reverse.join(' ') # => "World Hello"
Upvotes: 2