new to ruby, help with simple output
I am trying to learn ruby, and i am t开发者_StackOverflow中文版rying to do the exercise on this site and need help learn ruby
Write a program that asks for a number and a sentence and prints the sentence backwards that many times. It should:
puts "Enter A Number?"
repeatHello = gets
i = 0
begin
puts "hello world!" + i
end while i > repeatHello
You're making two mistakes in the code you pasted. The first is that you need to add 1 to i each time it loops. At the moment i is not increasing in value.
Within the loop (between begin and end) you need to increment i like so:
i += 1
(This shorthand for i = i + 1).
The second mistake is on the last line. Currently it reads 'do this while i is greater than repeatHello', but i starts at 0, so its not going to be greater.
You need to switch it around to
while i < repeatHello.
You should end up with some code like this:
puts "Enter A Number?"
number = gets
puts "Enter A Sentence?"
sentence = gets
i = 0
begin
puts sentence.reverse
i += 1
end while i < number
I can give you a clue (rather than doing it for ya ;) ). Grab the users input, and using the example of turning input into a number (number = gets.chomp.to_i
) use a loop (ex. 4.times do
) to output the reversed text that many times. You should be able to use this along with the help from that tutorial page to get this desired result.
EDIT WITH EXAMPLE (possibly more ruby-ish?)
puts "Enter A Number?"
number = gets.chomp.to_i
puts "Enter A Sentence?"
sentence = gets.chomp
number.times do
puts sentence.reverse
end
A very useful thing to learn about Ruby is that it almost never makes sense to just reproduce the structure you would have written in another language. In this case, for example, not only do you not need to manage your own counter in a loop, but you don't need to loop at all!
puts "Enter a number"
number = gets.chomp.to_i
puts "Enter a sentence"
sentence = gets
puts (sentence*number).reverse
精彩评论