0

At the moment I've got this code:

name, type = meth.to_s.match(/^(.+?)([=?]?)$/)[1..-1]

But it doesn't seem to be the best solution =\

Any ideas how to make it better? Thanks.

Manoj Govindan
  • 72,339
  • 21
  • 134
  • 141
Daniel
  • 4,272
  • 8
  • 35
  • 48
  • xyz= - setter, xyz? - checker, xyz - getter – Daniel Sep 18 '10 at 16:17
  • Can you be a little bit more precise in your specification: what's the "type" of the `==` method or the `===` method? What's the "type" of a method like `Kernel#puts`? – Jörg W Mittag Sep 18 '10 at 19:05
  • Are you familiar with `attr_reader` and similar methods which mean you don't have to write setters or getters unless they have complicated logic? – Andrew Grimm Sep 21 '10 at 00:05
  • i'm aware about class macroses and attr_* family, but this code resides in method_missing, so it has nothing to do with attr_* – Daniel Sep 21 '10 at 14:19

2 Answers2

1

The best option seems to be this: name, type = meth.to_s.split(/([?=])/)

Daniel
  • 4,272
  • 8
  • 35
  • 48
  • method "types" don't really exist, you're the only person in the whole history of the ruby universe to talk about them ;) – horseyguy Sep 19 '10 at 04:26
  • i know, i just don't know how to describe it, so i thought "method types" will be better than "method suffix" – Daniel Sep 20 '10 at 14:55
  • Don't listen to that guy, he's an idiot. You're on the ball, they're typically referred to as "Setters" and "Getters". – Robert Ross Dec 14 '11 at 02:13
0

This is roughly how I'd implement my method_missing:

def method_missing(sym, *args, &block)
  name = sym.to_s
  if name =~ /^(.*)=$/
    # Setter method with name $1.
  elsif name =~ /^(.*)\?$/
    # Predicate method with name $1.
  elsif name =~ /^(.*)!$/
    # Dangerous method with name $1.
  else
    # Getter or regular method with name $1.
  end
end

Or this version, which only evaluates one regular expression:

def method_missing(sym, *args, &block)
  name = sym.to_s
  if name =~ /^(.*)([=?!])$/
    # Special method with name $1 and suffix $2.
  else
    # Getter or regular method with name.
  end
end
Richard Cook
  • 32,523
  • 5
  • 46
  • 71