Created
April 26, 2012 03:29
-
-
Save DiveInto/2495479 to your computer and use it in GitHub Desktop.
ruby code style,checkout https://github.com/styleguide/ruby for more
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#== Never use for, unless you know exactly why. Most of the time iterators should be used instead. for is implemented in terms of each (so you're adding a level of indirection), but with a twist - for doesn't introduce a new scope (unlike each) and variables defined in its block will be visible outside it. | |
arr = [1, 2, 3] | |
# bad | |
for elem in arr do | |
puts elem | |
end | |
# good | |
arr.each { |elem| puts elem } | |
#== Never use then for multi-line if/unless. | |
# bad | |
if some_condition then | |
# body omitted | |
end | |
# good | |
if some_condition | |
# body omitted | |
end | |
#== Favor modifier if/unless usage when you have a single-line body. | |
# bad | |
if some_condition | |
do_something | |
end | |
# good | |
do_something if some_condition | |
#== Prefer {...} over do...end for single-line blocks. Avoid using {...} for multi-line blocks (multiline chaining is always ugly). Always use do...end for "control flow" and "method definitions" (e.g. in Rakefiles and certain DSLs). Avoid do...end when chaining. | |
names = ["Bozhidar", "Steve", "Sarah"] | |
# good | |
names.each { |name| puts name } | |
# bad | |
names.each do |name| | |
puts name | |
end | |
# good(chain call) | |
names.select { |name| name.start_with?("S") }.map { |name| name.upcase } | |
# bad | |
names.select do |name| | |
name.start_with?("S") | |
end.map { |name| name.upcase } | |
#== Use ||= freely to initialize variables. | |
# set name to Bozhidar, only if it's nil or false | |
name ||= 'Bozhidar' | |
#== Prefer %w to the literal array syntax when you need an array of strings. | |
# bad | |
STATES = ['draft', 'open', 'closed'] | |
# good | |
STATES = %w(draft open closed) | |
#== Use symbols instead of strings as hash keys. | |
# bad | |
hash = { 'one' => 1, 'two' => 2, 'three' => 3 } | |
# good | |
hash = { one: 1, two: 2, three: 3 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment