Last active
December 20, 2015 20:59
-
-
Save Ejhfast/6194662 to your computer and use it in GitHub Desktop.
Some sort-of-cool near miss examples
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
# 1: Implicit return of each block is thrown away | |
# => You probably want some kind of state change | |
list_of_lists = [ | |
["Ethan Fast", nil, "Lucy Wang", "Daniel Steffee"], | |
[2007, 2011, 2010, nil] | |
] | |
list_of_lists.each do |l| | |
l.compact # You probably meant compact!, which appears once. | |
end | |
# 2: Sort requires something approximating the <=> operator | |
# (It can be expressed as a lookup table, but that's pretty weird). | |
simple_list = [42,13,7,3] | |
table = Hash.new { |h,k| h[k] = {} } | |
simple_list.sort { |e1,e2| table[e1][e2] } | |
# 3: Implicit return block of map should probably not be nil | |
# => You usually want some kind of transformation | |
list_of_lists.map do |l| | |
my_func(l) | |
puts l | |
end | |
# 4: Dumb naming choice; array does sort of look like an array... | |
# (But it would be nice to find a cooler example) | |
pairs = [[1,2],[3,4]] | |
array = {} | |
pairs.each do |el| | |
array[el[0]] = el[1] | |
end | |
# 5: This works, since sort! returns the list, but not all bangs do this consistently | |
# Also, simple_list.min would work better... | |
simple_list.sort!.pop | |
# 6: Redundant operation. You could use slice to extract the element you want | |
# (first is unnecessary) | |
val = simple_list.slice(3).first | |
# 7: Canonical example of "type signature" mistake? | |
# (Which function to use for this) | |
Array.new([1,2,3],2) # Should be Array.new(2, [1,2,3]) => [[1,2,3],[1,2,3]] | |
# 8: Type signatures can distinguish between var0.field(var1) and var0.field = var1 | |
# E.g., setting the default of a Hash incorrectly | |
h = {} | |
h.default(0) # Should be h.default = 0 (or h = Hash.new(0)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
a = arr.each{|x| x*2}
is an alternative example to
arr.map{|x| something; puts x}
might be slightly better