-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathbraces_vs_do_end.rb
45 lines (32 loc) · 1.05 KB
/
braces_vs_do_end.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# The general convention is to use do..end for multi-line blocks and curly braces
# for single line blocks, but there is also a difference between the two that can
# be illustrated with this example:
puts [1, 2, 3].map { |k| k + 1 }
# 2
# 3
# 4
# => nil
puts [1, 2, 3].map do |k| k + 1; end
# <Enumerator:0x0000010a06d140>
# => nil
# This means that {} has a higher precedence than do ..end, so keep that in mind
# when deciding what you want to use. P.S: One more example to keep in mind while
# you develop your preferences. The following code:
task rake: pre_rake_task do
something
end
# Really means:
task(rake: pre_rake_task) { something }
# And this code:
task rake: pre_rake_task {
something
}
# Really means:
task rake: (pre_rake_task { something })
# So to get the actual definition that you want, with curly braces, you must do:
task(rake: pre_rake_task) do
something
end
# Maybe using braces for parameters is something you want to do anyways, but if
# you don 't it' s probably best to use do .. end in these cases to avoid this
# confusion.