我想弄清楚在Ruby
中使用多个参数的最佳方法。问题是我使用两种类型的参数:Event
和User
。有时,该方法需要一个User
:在Ruby中使用多个参数
postAccept.replaceVariables(sally)
有时需要两个Users
:
deleteGuest.replaceVariables(sally, tom)
有时它需要一个Event
和两个Users
:
addUserToEvent.replaceVariables(mEvent, tom, sally)
而在去年,有时它需要一个Event
和一个User
:
addnonbookable.replaceVariables(event1, carl)
以下是我在考虑到当前的方法做:
def replaceVariables(*event)
if event.size <=2
if event[0].include?('entryId')
event1 = event[0]
my = event[1]
else
my = event[0]
their = event[1]
end
else
event1 = event[0]
my = event[1]
their = event[2]
end
...
的问题是,我不能想出一个办法的user
和event
区分。在上面的例子中,我试图确定对象是否有特定的键或值,但我得到NoMethodError
。
有人能告诉我我做错了什么,或者让我知道保持动态和灵活的方法吗?
def replace_variables(*args)
events, users = args.group_by{ |p| p.class }.values_at(Event, User)
#now you have 2 arrays and can manipulate them
#...
end
这真是糟糕的风格。你应该用一种方法来编写你的方法,它们接受一小部分而且相当静态的参数。您应该为不同的调用模式实现多种方法,对这些值进行规范化,然后调用另一种实现实际逻辑的方法(如果需要)。 –
为什么该方法有时需要不同类型的对象? –
我这样做的原因是因为它是更简单的方法。该方法正在取代许多不同的环境变量。目前该方法是220行代码。如果我把它分解成两种方法,那会增加一倍。 – BlackHatSamurai