Matt Brooks wrote:
> I need a way to accomplish the following.  I can't figure out an elegant
> way, beating my head against the wall thinking about it.
> 
> I receive strings into a variable and want to check that string to see
> if it contains at least the beginning of another string.
> 
> 
> say original string is "CHLE,231,1", and i receive string I want to
> check against it.
> 
> I guess you could say the strings are comma separated within each string
> that I receive.
> 
> I need to know it matched if I receive "CHLE,231" or "CHLE,231,1" but if
> I get "CHLE,23" or "CHLE,231,2" these should not be matches, and should
> say nil.
> 
> 
> 
> For Example
> 
> blah = "CHLE,231,1"
> => "CHLE,231,1"
> 
> blah["CHLE,231,1"]
> => "CHLE,231,1"   * GOOD
> 
> blah["CHLE,231"]
> => "CHLE,231"     * GOOD
> 
> blah["CHLE,232"}
> => nil            * GOOD
> 
> blah["CHLE,231,2"]
> => nil            * GOOD
> 
> blah["CHLE,23"]
> => "CHLE,23"      * BAD, I want this to be NIL
> 
> 
> Thanks for the help!!!
> Matt

A possible solution (untested, and probably susceptible to lots of 
improvement):

class String
  def match_prefix(other)
    SEPARATOR = ','
    chunks = self.split SEPARATOR
    input = other.split SEPARATOR
      if input.size > chunks.size
        # can't match if we have more chunks in the input
        return false
      else
        # test the chunks we've got
        input.size.each_with_index do |chunk, i|
          if chunk != chunks[i]
            return false
          end
        end
      return true
  end
end

Best,
--
Marnen Laibow-Koser
http://www.marnen.org
marnen / marnen.org
-- 
Posted via http://www.ruby-forum.com/.