Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

loops - Why type-casting don't properly work with $. in Ruby?

I have a Ruby code as shown below, Try it online!

loop{p$.+=1r}

and another one, in which I just divide the 1r by 2 as shown below, Try it online!

loop{p$.+=1r/2}

As far as I can guess, the type-casting isn't working properly with $.. In the first case, it works correctly, but in the second one, it doesn't. strange!

So, why it works that way? Or, maybe my guess is wrong, then what is the actual issue, and how to resolve it?


Usually, Integer are up-casted to more complex data types, like in this code, it seems to work.

question from:https://stackoverflow.com/questions/65542125/why-type-casting-dont-properly-work-with-in-ruby

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

it works correctly, type of the $. variable is Integer

puts $..class. # => Integer

So right side of the addition will be casted to the Integer.
In first case 1r is casted to the Integer of value 1, so you can see value is changing.

In second case 1r/2 is casted to the Integer of value 0, so you don't see changes because adding zero will not change original value.

You can not change type of pre-defined global variable, just try $. = "text"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...