W
W
Wamsmer2019-01-28 20:04:51
ruby
Wamsmer, 2019-01-28 20:04:51

String interpolation in Ruby and the times, upto and downto methods. How to enter in a line?

There is a task. Output the word "Hi" to the console 10 times (from a new line) and append an exclamation mark to it. At each iteration, the number of Exclamation Points should increase by 1.
Example:
Hello!
Hey!!
Hey!!!
etc.
Wrote like this:

1.upto(10) {|x| puts"Hello #{x.times { print "!"}}"}

But I got a strange result:
!Hello1
!!Hello2
!!!Hello3
!!!!Hello4
Questions:
1. Why is the result of the expression x.times { print "!"} displayed first?
2. Why is x displayed if it is included in the code as part of a function?
3. Is it even possible to write this in one line with these methods?
There is a solution with a multiplication sign, but I want to understand why the data is displayed in such a sequence and with the x value. Thanks in advance for your replies.
1.upto(10) {|x| puts "Hello#{"!"*x}"}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
roswell, 2019-01-28
@Wamsmer

1. The expression #{ x.times... }in double quotes was expanded in the first place, but there inside -- print, how could it not be called. Hence the exclamation marks before Hello.
2. Any block in Ruby, including the one that #{ ... }returns the last calculated value (the result of the call x.times { ... }, in this case), therefore, after displaying the exclamation points and the Hello line, the interpreter substituted the result of its calculation instead of the expression.
3. The solution is already in the question.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question