在同一行初始化两个变量 [英] Initialize two variables on same line

查看:63
本文介绍了在同一行初始化两个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法找到有关此概念的权威示例或讨论.如果我的 Ruby 方法中有 2 个变量是数字,我需要将它们初始化为零.它们将用作计数器.这正常还是安全?它适用于我的测试.

I'm having trouble finding an authoritative example or discussion of this concept. If I have 2 variables in my Ruby method that are numbers, and I need to initialize them to zero. They will be used as counters. Is this OK or safe? It works in my tests.

取而代之的是:

foo = 0
bar = 0

你能做到吗?

foo = bar = 0

这似乎是一种节省线路但仍具有表现力的好方法.或者,这是一种不好的做法吗?我意识到我会牺牲一点可读性.但是,在小型 Rub​​y 方法(<10 行)中,这可能不是一个有效的问题.

It seems like a nice way to save on lines and still be expressive. Or, is this a bad practice? I realize I would be sacrificing readability a little. But, in a small Ruby method (<10 lines), that might not be a valid concern.

推荐答案

这行得通,但您应该知道它只对您的情况是安全的,因为您使用的是数字变量,这些变量在 Ruby 中是不可变的.例如,如果你用字符串尝试同样的事情,你可能会得到一些你意想不到的行为:

This works, but you should know that it's only safe for your situation because you're using the variables for numbers, which are immutable in Ruby. If you tried the same thing with a string, for example, you could end up with some behavior you didn't expect:

ruby-1.9.2-p180 :001 > foo = bar = "string"
 => "string" 
ruby-1.9.2-p180 :002 > foo.upcase!
 => "STRING" 
ruby-1.9.2-p180 :003 > bar
 => "STRING"

这篇关于在同一行初始化两个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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