简体   繁体   中英

Block/Proc with Include for Ruby

I'm trying to think of a way to do this as a proc. Essentially the only part of the code that is different is that on substring match their is a .include? instead of a check for equals.

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

I'm not sure if I remember how to code in Ruby elegantly, but what about something like this?

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

The function can then be called like this:

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

Modification from @busy_wait.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM