روبي: ما هي أفضل طريقة لمعرفة نوع الطريقة في method_missing؟

StackOverflow https://stackoverflow.com/questions/3742376

سؤال

في الوقت الحالي حصلت على هذا الرمز:

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

لكن لا يبدو أن الحل الأفضل =

أي أفكار كيف تجعلها أفضل؟ شكرًا.

هل كانت مفيدة؟

المحلول

يبدو أن الخيار الأفضل هو:name, type = meth.to_s.split(/([?=])/)

نصائح أخرى

هذا هو كيف سأطبق بلدي 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

أو هذا الإصدار ، الذي يقيم تعبيرًا منتظمًا واحدًا فقط:

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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top