我可以在Ruby中创建替代括号吗?

时间:2016-08-12 11:52:04

标签: ruby

我想拥有更大范围的括号。为了给出一个想法,我已经可以修改正常的方括号:

class City
 def initialize(city:)
   @city = city
 end

 def [](man) 
   print "I am #{man} of #{city}"
 end 
end

所以我能做到:

paris = City.new city: "Paris"
paris["George"] # ==> I am George of Paris

但是现在我想添加这样的新括号:

class City
 def initialize(city:)
  @city = city
 end

 def [M M](man) 
   print "I am man: #{man} of #{city}"
 end 

 def [W W](woman) 
   print "I am woman: #{woman} of #{city}"
 end
end

所以我可以这样做:

paris = City.new city: "Paris"
paris[M "George" M] # ==> I am man: George of Paris
paris[W "Lisa" W]  # ==> I am woman: Lisa of Paris

有可能吗?怎么样?

2 个答案:

答案 0 :(得分:1)

有一种方法可以做到这一点,但就像其他说明你不应该这样做。

class City
   def initialize(city:)
      @city = city
   end

   def [](type, name) 
     if type == :m
        print "I am man: #{name} of #{city}"
     else
       print "I am woman: #{name} of #{city}"
     end
   end 
end

city = City.new('Paris')
city[:m, 'George']

答案 1 :(得分:0)

通常使用参数化子类化来执行此操作。您首先创建一个代表一般人的Human类,然后告诉每个城市包含HumanLondon.CitizenDublin.citizen)的参数化子类。我将在这些示例中使用YSupport gem(gem install y_support)来保持代码简短,但您也可以使用纯Ruby轻松实现此行为。

require 'y_support/all'

class Human
  ★ NameMagic
  selector :sex
  def self.male; new :m end
  def self.female; new :f end
  def initialize sex; @sex = sex end
end

class City
  ★ NameMagic
  delegate :male, :female, to: "self.Citizen"
  def initialize
    param_class( { Citizen: Human }, with: { city: self } )
    class << self.Citizen
      def introduce_self
        "I am a #{{m: :man, f: :woman}[sex]} from #{city}."
      end
    end 
  end
end

注意param_class方法为每个城市创建Human的参数化子类,代表该城市的公民:

London, Paris = City.new, City.new
Tom = London.male
Lisa = Paris.female