Skip to content

Instantly share code, notes, and snippets.

@matstc
matstc / gist:c2177619376a2fcd494f
Created October 13, 2014 13:20
Example of Guard Clause
def divide x, y
raise "Cannot divide by zero" if y == 0
x / y
end
@matstc
matstc / gist:f27e3301e243c10fd8e9
Created October 13, 2014 13:22
Example of Not Using a Guard Clause
def divide x, y
if y == 0
raise "Cannot divide by zero"
else
x / y
end
end
@matstc
matstc / gist:3b3a324600016d3c5264
Last active August 29, 2015 14:07
Example of inline if
def previous
@trackIndex -= 1
@trackIndex = 0 if @trackIndex < 0
@play()
end
@matstc
matstc / gist:14943ebdd7d2afabb107
Created October 21, 2014 13:32
Example with temporary variables
def title_case string
words = string.split " "
capitalized_words = words.map {|w| w.capitalize}
title = capitalized_words.join " "
return title
end
@matstc
matstc / gist:12f0079c54ce5c43bbe4
Created October 21, 2014 13:33
Example with variable variables
def calculate_total items
sum = 0
for index in 0...items.length
sum += items[index].price
end
sum
end
@matstc
matstc / gist:01464cb0df33658828ea
Created October 21, 2014 13:34
Example without variable variables
def calculate_total items
items.map {|item| item.price}.reduce(&:+)
end
@matstc
matstc / gist:993b82f7a5623710e6fe
Created October 21, 2014 13:35
Example of heavy if branch
def comment_on_popularity
if !post.stars.empty?
if post.stars.count > 100
"Congratulations. Your post is very popular."
elsif post.stars.count > 50
"Well done. Your post is trending."
else
"Your post is doing well but could use a little attention."
end
else
@matstc
matstc / gist:8d693575d17f2e1e3f6c
Created October 21, 2014 13:36
Example of skinny if branch
def comment_on_popularity
if post.stars.empty?
"Your post is flying under the radar."
else
if post.stars.count > 100
"Congratulations. Your post is popular!"
elsif post.stars.count > 50
"Well done. Your post is trending."
else
"Doing well but could use a little attention."
@matstc
matstc / gist:3d933b340da467c8f352
Last active August 29, 2015 14:07
Example of an eager definition
def greet user
title = if user.admin?
"sir"
else
"you"
end
"Hello, #{title}!"
end
@matstc
matstc / gist:381a4521b2e5c9659813
Last active August 29, 2015 14:07
Example of late branching
def greet user
"Hello, %s!" % if user.admin?
"sir"
else
"you"
end
end