像这样分配多个变量是否正确 a = b = c = d = 5? [英] Is it right to assign multiple variables like this a = b = c = d = 5?

查看:36
本文介绍了像这样分配多个变量是否正确 a = b = c = d = 5?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

a = b = c = d = 5

puts (a) >> 5
puts (b) >> 5
puts (b) >> 5
puts (b) >> 5
a= a+1
puts (a) >> 6
puts (b) >> 5

我发现像这样分配值没有问题.我的问题是应该像上面给出的那样分配还是像这样分配?

I found there is no problem with the assigning of values like this. My question is should one assign like the one given above or like this?

a , b, c, d = 5, 5, 5, 5

推荐答案

这里需要注意的是,您的情况只能正常工作,因为数字在 Ruby 中是不可变的.您想对字符串、数组、散列或除数字以外的几乎任何其他内容执行此操作,因为它会创建对同一对象的多个引用,这几乎肯定不是您想要的:

The thing to be aware of here is that your case only works OK because numbers are immutable in Ruby. You don't want to do this with strings, arrays, hashes or pretty much anything else other than numbers, because it would create multiple references to the same object, which is almost certainly not what you want:

a = b = c = d = "test"
b << "x"
=> "testx"
a
=> "testx"

而并行形式对所有类型都是安全的:

Whereas the parallel form is safe with all types:

a,b,c,d = "test","test","test","test"
=> ["test", "test", "test", "test"]
b << "x"
=> "testx"
a
=> "test"

这篇关于像这样分配多个变量是否正确 a = b = c = d = 5?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆