Skip to content

Instantly share code, notes, and snippets.

@elle
Last active March 7, 2016 16:14
Embed
What would you like to do?
playing-with-structs
# POODR page 28
Wheel = Struct.new(:rim, :tire)
def wheelify(data)
data.collect {|cell| Wheel.new(cell[0], cell[1])}
end
# POODR Page 32
class Gear
attr_reader :chainring, :cog, :wheel
def initialize(chainring, cog, rim, tire)
@chainring = chainring
@cog = cog
@wheel = Wheel.new(rim, tire)
end
...
Wheel = Struct.new(:rim, :tire) do
def diameter
rim + (tire * 2
end
end
end
# Me playing around
> Agent = Struct.new(:listing_id, :selling_id)
=> Agent
> t1 = Agent.new(1, 2)
=> #<struct Agent listing_id=1, selling_id=2>
> t1.listing_id
=> 1
> t2 = Agent.new(1, 3)
=> #<struct Agent listing_id=1, selling_id=3>
> t3 = Agent.new(2, 4)
=> #<struct Agent listing_id=2, selling_id=4>
> t4 = Agent.new(2, 5)
=> #<struct Agent listing_id=2, selling_id=5>
> ts = [t1, t2, t3, t4]
=> [#<struct Agent listing_id=1, selling_id=2>, #<struct Agent listing_id=1, selling_id=3>, #<struct Agent listing_id=2, selling_id=4>, #<struct Agent listing_id=2, selling_id=5>]
> selling_ids = ts.select { |t| t.listing_id == 1 }.map &:selling_id
=> [2, 3]
> ts.select { |t| selling_ids.include? t.listing_id }.map(&:selling_id)
=> [4, 5]
> ts.select { |t| selling_ids.include? t.listing_id }.map(&:selling_id).count
=> 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment