Archive for the ‘smellcode’ Category
if mortgage.class==FixRateMortgage mortgage.change_rate_not_allowed else mortgage.rate=rate end
The code below is more idiomatic in Ruby.
class Mortgage attr_accessor :rate end class FixedRateMortgage < Mortgage def initialize() @rate=5 end def rate=(rate) change_rate_not_allowed end def change_rate_not_allowed puts "The rate in a fixed rate mortage can not be change" end end
Sending the method rate= to either kind of classes will result in the appropriate behaviour.
Originally blocks did not have truly local variables. The block
parameters were really local variables in the enclosing method.
x=0 1.upto 100 do |z| x = x+z end x #=> 5050
You should never, never, never iterate over a collection which the iteration loop somehow modifies. Elements of the collection will be moved during the iteration. Elements might be missed or handled twice.
b=(1..10).collect # => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] b.each do |elem| b.delete elem end #=> [2, 4, 6, 8, 10]