[英]What is the role of `to_s` method on `x`?
This code will generate a positive even integer ladder: 此代码将生成一个正偶数梯形图:
puts "Enter an integer"
n = gets
def pattern(n)
2.step(n, 2).map {|x| x.to_s * x}.join("\n")
end
I have been struggling to figure out what to_s
does to the code. 我一直在努力弄清楚
to_s
对代码的作用。
It converts a fixnum into a string. 它将fixnum转换为字符串。 It is particularly necessary because it is followed by the
* x
operation, which multiplies a string. 这是特别必要的,因为它后面是
* x
运算,该运算将字符串相乘。 If to_s
had not been applied, then * x
will multiply the fixnum arithmetically. 如果尚未应用
to_s
,则* x
将以算术方式乘以fixnum。
The x.to_s
is needed so that String's *
method is called and not Integer's *
method. 需要
x.to_s
,以便调用String的*
方法,而不是Integer的*
方法。
> i = 2
=> 2
> i * 2
=> 4
> s = '2'
=> "2"
> s * 2
=> "22"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.