w1d3
Today we learned about code smell, some finer details on ruby's objects and variable assignment, and default hash value assignment. My partner and I worked on a couple of games today (Mastermind and hangman), and definitely used this knowledge for coding and debugging.
code smells some of the ones that were highlighted in today's lecture were duplicate code, long methods, speculative generality (coding for potential future needs rather than focusing on the current requirements of a project), and god objects (classes that know too much about other classes).
immutable vs mutable objects -- some object types are immutable (fixnums and symbols), meaning they cannot be changed. Others (e.g. strings and arrays) can be changed by certain methods so you must be careful not to haphazardly change things out from under your variables.
assignment vs mutation -- when variables are assigned a value, this means that they point at an object id. When the variable is later referenced, ruby retrieves the object whose id the variable points to. When some methods are called upon a variable, they create a new object_id and reassign the variable to this. Since fixnums and symbols are immutable, all of their methods will create new object ids. However, other methods may actually mutate the object that the variable points to and could cause unintended consequences. Here's an example:
a = 'small' b = a puts a # => 'small' puts b # => 'small' a[2] = 'e' # mutates the string (which a and b both point to) puts a # => 'smell' puts b # => 'smell' a += 'y cat' #reassigns a (a = a + 'y cat') puts a # => 'smelly cat' puts b # => 'smell'
default hash values -- if your default hash value is an immutable type, pass the value as an argument. If your default value is mutable, you must pass it in as a block. This will create a new object each time a new key is called rather than the same object. For instance:
# only use this syntax when default value is an immutable type (fixnum, symbol) # this will assign every new key the same array object h = Hash.new([]) # this will assign every new key a new array object, but will not save it immediately g = Hash.new() { [] } #each time a new key is referenced, the block will assign it a new array object h = Hash.new() { |hash, key| hash[key] = [] }
















