Im currently going through a book and there is a pice of code that I don’t quite understand:
class RevealingReferences
attr_reader :wheels
def initialize(data)
@wheels = wheelify(data)
puts data
end
def diameters
wheels.collect do |wheel|
puts "test"
wheel.rim + (wheel.tire*2)
end
end
Wheel = Struct.new(:rim, :tire)
def wheelify(data)
data.collect{|cell|
Wheel.new(cell[0], cell[1])}
end
end
end
puts RevealingReferences.new([3,2,5,8]).diameters
and I get the following output:
3
2
5
8
test
test
test
test
3
2
1
0
1) Now the 3,2,5,8 I understand, but why does not display in array format [3,2,5,8] rather its being displayed one int at a time.
2) Also, in the wheels.collect block, the output prints “test” twice before putting in the output, should it not be “test” value “test” value
3) Also, the answer 3,2,1,0 don’t make any sense, when I set @wheels should wheels not be a collection of an array of 2 elements rather then 4?
This is due to how
putsworks. When it sees an array, it prints the#to_sof each elementIf you want it to look like an array, you should inspect it before printing it
There’s also a shorthand for this, the method
pThe only thing printing the values is the puts statement on the return value of
diameters, so they won’t print until after they have been collected. If you wanted to print it after each test, you should probably do something likeWhich would print:
Based on what you’re saying here, I assume your data is not in the format you intended. You’re passing in
[3,2,5,8], but this implies that you meant to pass in[[3,2],[5,8]], or to map across every pair of values:The reason it isn’t doing what you think is because without doing one of these, the
cellvariable is actually just a number. Since numbers have the brackets method defined on them, they wind up working in this case. But the brackets method just returns 1 or 0, depending on the bit (base 2) at that position:So in the case of 3,
wheel.rim + (wheel.tire*2)becomesAnd in the case of 2:
And 5:
And 8:
Which is why
diametersreturns[3, 2, 1, 0], explaining the last four digits you see.