Rubyize this : 4th edition

The 3rd edition marked the beginning of a new association between Rubyize this and RefactorMyCode. I did things in a rather clumsy manner, telling people about how cool RmC was while asking them to use pastie to submit their refactored version of the code. At that time I didn’t realize that RmC and Rubyize this were ready to work together.
Well, RmC is now the official way to submit your rubyized solution. With the trackback system in place, a link to your refactored code will appear here at the moment you hit the submit button on RmC.
Before diving into the 4th edition, I’d like to take a moment to talk about the results of the 3rd one. We started with something pretty ugly that turned onto something pretty awesome!. On a side note, I really liked how some participants transformed the already mean sentence into something even meaner. As an exemple, the test sentence was : « You truly are a moron, sir! » and someone changed it to « you truly are a stupid moron sir! ». Someone else add fuel to the fire by writing « you truly are a ‘stupid’ moron, stupid sir! ». And finally, someone went as far as to write : « Stupid wabbit! Stupid, stupid, stupid! ». The situation was completely uncontrollable!
Enough said. Let’s get the ball rolling.
I have an array of insects and I want to be able to display on the screen the name, the iq and the annoyance factor of every members of a certain type. This “solution” works but has a ruby rating of 0.5/5. Moreover, it only works for butterflies… which feels rather incomplete and limiting. Remove stuff, add stuff and move stuff around. This dumb code must get smart and pretty!

class Bug
	attr_accessor :type
	attr_accessor :name
	attr_accessor :iq
	attr_accessor :annoyance_factor
	def initialize(name,type,iq,annoyance_factor)
		if !type
			@type="spider"
		else
			@type=type
		end
		if !name
			@name="unnamed"
		else
			@name=name
		end
		if !iq
			@iq = 8
		else
			@iq = iq
		end
		if !annoyance_factor
			@annoyance_factor = 4
		else
			@annoyance_factor = annoyance_factor
		end
	end
end
def keep_butterflies(bugs)
	butterflies = Array.new
	bugs.each do |bug|
		if bug.type == "butterfly"
			butterflies.push(bug)
		end
	end
	return butterflies
end
#create some bugs!
bugs = Array.new
bugs.push(Bug.new("ron","spider","4","2"))
bugs.push(Bug.new("don","spider","2","3"))
bugs.push(Bug.new("jake","ant","9","4"))
bugs.push(Bug.new("chris","ladybug","2","4"))
bugs.push(Bug.new("fred","cockchaffer","0","5"))
bugs.push(Bug.new("greg","butterfly","2","0"))
bugs.push(Bug.new("jason","butterfly","0","2"))
butterflies=keep_butterflies(bugs)
butterflies.each do |butterfly|
	puts "I am a butterfly and my name is #{butterfly.name}. I have an IQ of #{butterfly.iq} and an annoyance factor of #{butterfly.annoyance_factor}"
end

Give it a shot now!

23 thoughts on “Rubyize this : 4th edition

Leave a Reply to Daniel Haran Cancel reply

Your email address will not be published. Required fields are marked *