Check if string contains any substring in an array in Ruby

后端 未结 5 1497
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-28 12:25

I am using the Tmail library, and for each attachment in an email, when I do attachment.content_type, sometimes I get not just the content type

相关标签:
5条回答
  • 2020-12-28 12:48

    So if we just want existence of a match:

    VALID_CONTENT_TYPES.inject(false) do |sofar, type| 
        sofar or attachment.content_type.start_with? type
    end
    

    If we want the matches this will give the list of matching strings in the array:

    VALID_CONTENT_TYPES.select { |type| attachment.content_type.start_with? type }
    
    0 讨论(0)
  • 2020-12-28 12:55

    If image/jpeg; name=example3.jpg is a String:

    ("image/jpeg; name=example3.jpg".split("; ") & VALID_CONTENT_TYPES).length > 0
    

    i.e. intersection (elements common to the two arrays) of VALID_CONTENT_TYPES array and attachment.content_type array (including type) should be greater than 0.

    That's at least one of many ways.

    0 讨论(0)
  • 2020-12-28 12:56

    There are multiple ways to accomplish that. You could check each string until a match is found using Enumerable#any?:

    str = "alo eh tu"
    ['alo','hola','test'].any? { |word| str.include?(word) }
    

    Though it might be faster to convert the array of strings into a Regexp:

    words = ['alo','hola','test']
    r = /#{words.join("|")}/ # assuming there are no special chars
    r === "alo eh tu"
    
    0 讨论(0)
  • 2020-12-28 13:05
    # will be true if the content type is included    
    VALID_CONTENT_TYPES.include? attachment.content_type.gsub!(/^(image\/[a-z]+).+$/, "\1") 
    
    0 讨论(0)
  • 2020-12-28 13:08

    I think we can divide this question in two:

    1. How to clean undesired data
    2. How to check if cleaned data is valid

    The first is well answered above. For the second, I would do the following:

    (cleaned_content_types - VALID_CONTENT_TYPES) == 0
    

    The nice thing about this solution is that you can easily create a variable to store the undesired types to list them later like this example:

    VALID_CONTENT_TYPES = ['image/jpeg']
    cleaned_content_types = ['image/png', 'image/jpeg', 'image/gif', 'image/jpeg']
    
    undesired_types = cleaned_content_types - VALID_CONTENT_TYPES
    if undesired_types.size > 0
      error_message = "The types #{undesired_types.join(', ')} are not allowed"
    else
      # The happy path here
    end
    
    0 讨论(0)
提交回复
热议问题