Skip to content
This repository was archived by the owner on Nov 30, 2024. It is now read-only.

Commit a561351

Browse files
author
pritam1994
committed
ruby coding style added
1 parent 806c973 commit a561351

File tree

1 file changed

+123
-1
lines changed

1 file changed

+123
-1
lines changed

ruby.md

Lines changed: 123 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,123 @@
1-
# Ruby
1+
# Ruby
2+
3+
## Syntax
4+
5+
* Never use `for`, unless you know exactly why. You can use `each` instead of `for`.
6+
7+
```ruby
8+
arr = [1, 2, 3]
9+
10+
# bad
11+
for element in arr do
12+
puts element
13+
end
14+
15+
# good
16+
arr.each { |element| puts element }
17+
```
18+
19+
* Never use `then` for multi-line `if/unless`
20+
21+
```ruby
22+
# bad
23+
if some_condition then
24+
# do something
25+
end
26+
27+
#good
28+
if some_condition
29+
# do something
30+
end
31+
```
32+
33+
* Use ternary operator (`?:`) over `if/then/else/end` constructs for single line conditions.
34+
35+
```ruby
36+
# bad
37+
result = if some_condition then something else something_else end
38+
39+
# good
40+
result = some_condition ? something : something_else
41+
```
42+
43+
* Always use `&&` and `||` instead of `and` and `or` keywords.
44+
45+
* Avoid multi-line `?:`(ternary operator), use `if/unless` instead.
46+
47+
* For single `if/unless` bolck write it in a single line.
48+
49+
```ruby
50+
# bad
51+
if some_condition
52+
do_something
53+
end
54+
55+
# good
56+
do_something if some_condition
57+
```
58+
59+
* Never use `unless` with `else`. Write it inside `if-else` block
60+
61+
```ruby
62+
# bad
63+
unless success?
64+
puts "failure"
65+
else
66+
puts "success"
67+
end
68+
69+
# good
70+
if success?
71+
puts "success"
72+
else
73+
puts "failure"
74+
end
75+
```
76+
77+
* Do not use parentheses around the condition of an `if/unless/while`.
78+
79+
```ruby
80+
# bad
81+
if (x > 5)
82+
# do something
83+
end
84+
85+
# good
86+
if x > 5
87+
# do something
88+
end
89+
```
90+
91+
* Avoid `return` where not required.
92+
93+
```ruby
94+
# bad
95+
def some_method(arr)
96+
return arr.size
97+
end
98+
99+
# good
100+
def some_method(arr)
101+
arr.size
102+
end
103+
```
104+
105+
* use `%w` freely.
106+
107+
```ruby
108+
# bad
109+
arr = ["one", "two", "three"]
110+
111+
# good
112+
arr = %w(one two three)
113+
```
114+
115+
## Naming
116+
117+
* use `snake_case` for methods and variables.
118+
119+
* use `CamelCase` for classes and modules.
120+
121+
* Constants are written in all uppercase with underscores to separate words. like: `A_CONST`
122+
123+

0 commit comments

Comments
 (0)