Talking to yourself is bad mmkay?

A lot of languages encourage talking to yourself. Lots of OO PHP code is sprinkled with code that looks like $this->foo_method();. In some languages it's necessary. Ruby isn't one of them.

class Foo
  def bar
    # Why are you talking to yourself?!
    @thingy = self.foo
  end

  def foo
    "QUUX!"
  end
end

The code above could be written without self at all.

class Foo
  def bar
    @thingy = foo
  end

  def foo
    "QUUX!"
  end
end

While this is a (very) trivial example, it makes a huge difference on larger code-bases. Give it a try: if you don't talk to yourself your code will look less crazy.

Only one caveat: when you're doing assignment you'll need to talk to yourself unless you're doing a local assignment.

class Foo
  attr_accessor :thingy

  def bar
    # This will assign to a local variable.
    thingy = foo
  end

  def foo
    "QUUX!"
  end
end
class Foo
  attr_accessor :thingy

  def bar
    # This will call Foo#thingy=
    self.thingy = foo
  end

  def foo
    "QUUX!"
  end
end

Commenting is closed for this article.

About the boy

A picture of Craig in grayscale

Craig Webster is a software engineer living in London. He usually works with Ruby although sometimes he sneaks in some Erlang or JavaScript. He's into rock climbing, snowboarding, skating, photography and fencing. Yes, this does mean he has a sword.

Near here you'll find Craig's homepage, contact details, PGP key and keysigning policy, and talks.

Licence

The entire content of this blog is public domain. Use it however you fancy. You don't even need to attribute it to me, although it would be nice if you did. Just don't sue me and we'll all be happy.

I Work With Rails

Recommend Me

My Travels

I go places. Do you go places too? Let's meet up!.