什么是“Ruby 方式”?对齐变量赋值? (代码风格问题)
假设我有这段未受污染的代码:
some_var = Hash.new
some_var[:name] = "blah"
some_var[:address] = "101 blahblah lane"
another = "Olly olly oxen free!"
Ruby 让它变得漂亮的方法是什么?
选项 1:保持原样
选项 2:对齐相关内容
some_var = Hash.new
some_var[:name] = "blah"
some_var[:address] = "101 blahblah lane"
another = "Olly olly oxen free!"
选项 3:对齐所有内容
some_var = Hash.new
some_var[:name] = "blah"
some_var[:address] = "101 blahblah lane"
another = "Olly olly oxen free!"
选项 4:??????
谢谢!!
Say i have this untainted code:
some_var = Hash.new
some_var[:name] = "blah"
some_var[:address] = "101 blahblah lane"
another = "Olly olly oxen free!"
What is the ruby way of making it pretty?
option 1: Leave it as is
option 2: Align related things
some_var = Hash.new
some_var[:name] = "blah"
some_var[:address] = "101 blahblah lane"
another = "Olly olly oxen free!"
option 3: Align all the things
some_var = Hash.new
some_var[:name] = "blah"
some_var[:address] = "101 blahblah lane"
another = "Olly olly oxen free!"
option 4: ?????
Thanks!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在你的例子中使用哈希我会做另一个版本:
或者使用 Ruby 1.9
Using Hashes as in your example I would do another version:
or with Ruby 1.9
我真的不喜欢#2 或#3。当你排列这样的东西时,你就将它们组合在一起。即使它们是“对称的”,这也完全不是您在变量赋值中想要的。就像
视觉上一样,您将 a、foobar 和 baz 分组,并将 1、2 和 3 分组。即使 1、2 和 3 相关,它们仍然应该与其标签分组,显示它们相关可以通过以下方式完成作业周围的有效空白。
现在,数据结构是你确实想要分组的东西的一个例子
,在我看来,它比这更难阅读,
这是一种情况,但我有一个#4给你。
Object#tap 将产生您点击到块中的东西,并将该块评估为您点击的东西。因此,在该示例中,Hash.new 被生成,被块修改,然后返回并分配给 some_var。与我一起工作的一些人绝对讨厌它,但我发现它在说“这里的所有内容都与初始化这个表达式直接相关”方面做得非常出色
I really don't like #2 or #3. When you align stuff like that, you are grouping things together. Even if they are "symmetrical", that is totally not what you want in variable assignment. like
visually, you are grouping a, foobar, and baz, and grouping 1, 2, and 3. Even if 1, 2, and 3 are related, they should still be grouped with their labels, showing they are related can be accomplished by effective whitespace around the assignments.
Now, datastructures are an example of something you DO want to group
is (imo) way harder to read then
This is sort of situational, but I have a #4 for you.
Object#tap will yield the thing you tap into the block, and evaluate the block to be the thing that you tapped. So in that example, Hash.new gets yielded in, modified by the block, and then returned to be assigned to some_var. Some people I work with absolutely hates it, but I find it does a fantastic job of saying "Everything in here is directly related to initializing this expression"
恕我直言,1 是最常见的一种,但我肯定见过 2。另外,至少在一份风格指南中也提到了后一种:
http://en.opensuse.org/openSUSE:Ruby_coding_conventions#Assignment
IMHO 1 would be the most common one, but I've definitely seen 2. Plus the latter one is also mentioned in at least one style guide:
http://en.opensuse.org/openSUSE:Ruby_coding_conventions#Assignment