Skip to content

Instantly share code, notes, and snippets.

@fj
Created July 19, 2012 04:20
Show Gist options
  • Save fj/3140725 to your computer and use it in GitHub Desktop.
Save fj/3140725 to your computer and use it in GitHub Desktop.
Unsolvable Ruby Problems example

This example just uses composition: define the methods you like on an Extended object and use those.

class Extended
  def initialize(array)
    @array = array
  end

  def scale(k)
    self.tap do |o|
      o.array.map! { |e| e * k }
    end
  end

  def array
    @array
  end
end

Now you can do:

load '/tmp/example.rb'
 # => true
e = Extended.new([4, 5, 67])
 # => #<Extended:0x00000000fc3aa0 @array=[4, 5, 67]>
e.scale 5
 # => #<Extended:0x00000000fc3aa0 @array=[20, 25, 335]>
e.array
 # => [20, 25, 335]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment