开发者

What is the "Ruby way" to align variable assignments? (code style question)

开发者 https://www.devze.com 2023-04-07 17:46 出处:网络
Say i have this untainted code: some_var = Hash.new some_var[:name] = \"blah\" some_var[:address] = \"101 blahblah lane\"

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            = "O开发者_如何学Clly olly oxen free!"

option 4: ?????

Thanks!!


Using Hashes as in your example I would do another version:

some_var = {
  :name    => "blah",
  :address => "101 blahblah lane",
}
another = "Olly olly oxen free!"

or with Ruby 1.9

some_var = {
  name:    "blah",
  address: "101 blahblah lane",
}
another = "Olly olly oxen free!"


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

a      = 1
foobar = 2
baz    = 3

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

some_method([[1, "foo"],
  [2, "bar"],
  [3, "baz"]])

is (imo) way harder to read then

some_method([[1, "foo"],
             [2, "bar"],
             [3, "baz"]])

This is sort of situational, but I have a #4 for you.

some_var = Hash.new.tap do |h|
  h[:name] = "blah"
  h[:address] = "101 blahblah lane"
end

another = "Olly olly oxen free!"

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"


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:

When multiple symmetrical assignments are on lines one after another, align their assignment operators. On the other hand, do not align assignment operators of unrelated assignments which look similar just by coincidence.

Rationale: Alignment helps reader recognize that the assignments are related or symmetrical.

http://en.opensuse.org/openSUSE:Ruby_coding_conventions#Assignment

0

精彩评论

暂无评论...
验证码 换一张
取 消