17 - implementing class and singleton methods.rb

来自「O Reilly Ruby Cookbook source code」· RB 代码 · 共 61 行

RB
61
字号
class Regexp  def Regexp.is_valid?(str)    begin      compile(str)      valid = true    rescue RegexpError      valid = false    end  endendRegexp.is_valid? "The horror!"                     # => trueRegexp.is_valid? "The)horror!"                     # => false#---def Fixnum.random(min, max)  raise ArgumentError, "min > max" if min > max  return min + rand(max-min+1)endFixnum.random(10, 20)                             # => 13Fixnum.random(-5, 0)                              # => -5Fixnum.random(10, 10)                             # => 10Fixnum.random(20, 10)                             # ArgumentError: min > max#---company_name = 'Homegrown Software'def company_name.legalese  return "#{self} is a registered trademark of ConglomCo International."endcompany_name.legalese# => "Homegrown Software is a registered trademark of ConglomCo International."'Some Other Company'.legalese# NoMethodError: undefined method `legalese' for "Some Other Company":String#---class Button  #A stub method to be overridden by subclasses or individual Button objects  def pushed  endendbuttonA = Button.newdef buttonA.pushed  puts "You pushed me! I'm offended!"endbuttonB = Button.newdef buttonB.pushed  puts "You pushed me; that's okay."endButton.new.pushed#buttonA.pushed# You pushed me! I'm offended!buttonB.pushed# You pushed me; that's okay.#---

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?