低效的Ruby方法命名:将命名空间作为参数传递,作为调用方法的一种方式

低效的Ruby方法命名:将命名空间作为参数传递,作为调用方法的一种方式,ruby,methods,namespaces,arguments,rake-task,Ruby,Methods,Namespaces,Arguments,Rake Task,在Ruby中必须有一种更有效的方法来实现这一点。我有一个方法列表,这些方法可以在多个站点上获取相同的内容(标题、价格),但根据每个商店的代码,它们的方式略有不同。例如: def store1_get_title def store1_get_price def store2_get_title def store2_get_price def store3_get_title def store3_get_price 调用所有这些函数时,我只希望使用一个泛型调用,比如说一个“namespa

在Ruby中必须有一种更有效的方法来实现这一点。我有一个方法列表,这些方法可以在多个站点上获取相同的内容(标题、价格),但根据每个商店的代码,它们的方式略有不同。例如:

def store1_get_title
def store1_get_price

def store2_get_title
def store2_get_price

def store3_get_title
def store3_get_price
调用所有这些函数时,我只希望使用一个泛型调用,比如说一个“namespace”参数来调用这些方法中的任何一个,而不必键入所有方法,比如:

for get_all_stores().each do |store|
     store::get_title
     store::get_price
end
…这将调用store1\u get\u title、store1\u get\u price、store2\u get\u title、store2\u get\u price,就像我想要的那样。有没有这样或更好的方法

希望这是有道理的。谢谢你的意见


编辑:这些任务在rake任务代码中。

这是类的完美用法。如果您发现两个商店使用相同的软件为它们提供动力(可能是Yahoo commerce或EBay商店),您可以使用不同的参数创建类的实例

class Amazon
  def get_price; end
  def get_title; end
end

class Ebay
  def initialize seller; end
  def get_price; end
  def get_title; end
end

[Amazon.new, Ebay.new("seller1"), Ebay.new("seller2")] each do |store|
   store.get_price
   store.get_title
end

您可以在任何其他面向对象语言中通过定义所有存储实现/继承的基类或接口来实现这一点。

这是类的完美用法。如果您发现两个商店使用相同的软件为它们提供动力(可能是Yahoo commerce或EBay商店),您可以使用不同的参数创建类的实例

class Amazon
  def get_price; end
  def get_title; end
end

class Ebay
  def initialize seller; end
  def get_price; end
  def get_title; end
end

[Amazon.new, Ebay.new("seller1"), Ebay.new("seller2")] each do |store|
   store.get_price
   store.get_title
end

您可以在任何其他面向对象语言中通过定义所有存储实现/继承的基类或接口来实现这一点。

我不理解应用程序的逻辑。也许您应该考虑一个类定义(参见KenBlooms的答案)

不过,您可以尝试使用
send
进行动态调用:

def store1_get_title
  p __method__
end
def store1_get_price
  p __method__
end

def store2_get_title
  p __method__
end
def store2_get_price
  p __method__
end

def store3_get_title
  p __method__
end
def store3_get_price
  p __method__
end

all_stores = ['store1', 'store2', 'store3']
all_stores.each do |store|
  send("#{store}_get_title")
  send("#{store}_get_price")
end
您没有定义“获取所有存储”返回的内容。在我的示例中,我使用了字符串。您可以添加一些语法糖并扩展字符串(我不建议这样做)


最后一句话。你写的

for get_all_stores().each do |store|

每个
就足够了<
for
不像ruby,与
每个
组合在一起,我觉得它不合理。

我不理解您的应用程序的逻辑。也许您应该考虑一个类定义(参见KenBlooms的答案)

不过,您可以尝试使用
send
进行动态调用:

def store1_get_title
  p __method__
end
def store1_get_price
  p __method__
end

def store2_get_title
  p __method__
end
def store2_get_price
  p __method__
end

def store3_get_title
  p __method__
end
def store3_get_price
  p __method__
end

all_stores = ['store1', 'store2', 'store3']
all_stores.each do |store|
  send("#{store}_get_title")
  send("#{store}_get_price")
end
您没有定义“获取所有存储”返回的内容。在我的示例中,我使用了字符串。您可以添加一些语法糖并扩展字符串(我不建议这样做)


最后一句话。你写的

for get_all_stores().each do |store|
每个
就足够了
for
不像ruby,并且与
每个
组合在一起,我觉得它不合理