简体   繁体   English

x上的to_s方法的作用是什么?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM