2013-08-15 56 views
0

我正试图想办法做到这一点,作为一个proc。本质上,唯一不同的部分是在子字符串上匹配它们是.include?而不是检查等于。包含红宝石的块/程序

def check_exact_match(lead_attribute, tracker_attribute) 
    return true if tracker_attribute.nil? 
    return true if lead_attribute.downcase == tracker_attribute.downcase 
    false 
end 


def check_substring_match(lead_attribute, tracker_attribute) 
    return true if tracker_attribute.nil? 
    return true if lead_attribute.downcase.include? tracker_attribute.downcase 
    return false 
end 
+1

请注意'如果cond1返回true;如果cond2返回true;假'也可以写成'cond1 ||' cond2'。 – sepp2k

回答

1

我不确定我是否记得如何在Ruby中优雅地编写代码,但是这样的事情呢?

def check­_match(lea­d_attribut­e, track­er_attribu­te)­ 
    track­er_attribu­te.nil? or yield lead_­attribute,­ track­er_attribu­te 
end 

该函数然后可以调用这样的:从@busy_wait

check_match("abcd", "bd") { |l, t| l.downcase == t.downcase } 
check_match(la, ta) { |l, t| l.downcase.include? t.downcase } 
+0

我知道OP说他想要一个proc,但是如果它使用了一个块,这会更加地道。 – sepp2k

+0

@ sepp2k:我不知道,在我脑海里,一个街区并不真正代表一个谓词。 – idoby

+1

许多方法都将块作为谓词('select','find','all?','any?')。我想不出一个以lambda/proc作为谓词的单一标准库方法(实际上,我认为只需要一个lambda的唯一标准库方法是'Hash#default_proc =',这只是因为它在语法上不可能取得块)。 – sepp2k

0

改性。

def check­_match(lea­d_attribur­e, track­er_attribu­te, &condition)­ 
    track­er_attribu­te.nil? or condition.­call(lead_­attribute,­ track­er_attribu­te) 
end 

def check_exact_match(lead_attribute, tracker_attribute) 
    check_match(lea­d_attribur­e, track­er_attribu­te) { |l, t| l.downcase == t.downcase } 
end 

def check_substring_match(lead_attribute, tracker_attribute) 
    check_match(lea­d_attribur­e, track­er_attribu­te) { |l, t| l.downcase.include? t.downcase } 
end