效率低下的Ruby方法命名:将名称空间作为参数传递,作为调用方法的方法

hee*_*313 0 ruby methods arguments namespaces 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
Run Code Online (Sandbox Code Playgroud)

当调用所有这些函数时,我只想要一个带有"namespace"参数的泛型调用来调用这些方法中的任何一个,而不必输入所有这些,例如:

for get_all_stores().each do |store|
     store::get_title
     store::get_price
end
Run Code Online (Sandbox Code Playgroud)

...会像我想的那样调用store1_get_title,store1_get_price,store2_get_title,store2_get_price.有这样的事情或更好的方法吗?

希望有道理.感谢您的任何意见!

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

Ken*_*oom 5

这是课程的完美用途.如果您发现两个具有相同软件的商店(可能是Yahoo商业或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
Run Code Online (Sandbox Code Playgroud)

您可以通过定义所有存储实现/继承的基类或接口,在任何其他面向对象语言中执行此操作.