Skip to content
Aditya Bhargava edited this page Sep 18, 2013 · 8 revisions

It's not obvious what a class initialize should return: self or nil?

initialize returns the value of the last statement. For example, here's a correct contract:

class Foo
  Contract nil => Num
  def initialize
    @bar = 1
  end
end

Note: you might want to return self yourself so you can write statements like Foo.new.bar = "asd":

class Foo
  Contract nil => Foo
  def initialize
    @bar = 1
    self
  end
end

But this is something you have to do yourself, ruby will not do this for you.

It's not obvious what a class setter should return

Again, it will return the value of the last statement, but you might want to return the object instead so you can chain method calls:

Contract String => String
def bar=val
  @bar = val
end

It's not obvious if a function argument which is assigned a default value in the signature should be contracted as String (say) or Or[String, nil]

Use String:

Contract String => nil
def hello name="adit"
  p "hello, #{name}!"
end

hello
Clone this wiki locally