Saturday, 15 August 2015

ruby - Scanning through a hash and return a value if true -


Based on my hash, I want to match it if it is in the string:

 < Code> def conv str = "I can only have one, two or sixty" hash = {: one => 1 ,: 2 = & gt; 2 ,: six = & gt; 6,: sixty = & gt; 60} str.match (Regexp.union (hash.keys.to_s)) Finally conv # = & gt; & Lt; Empty & gt;  

The above does not work but it only matches "A":

  str.match (Regexp.union (hash [0] To_s))  

Edit:

Any ideas how to match "a", "two" and sixty exactly in the string ?

If my string is "sixty" then it returns "6" and should not be based on the answer of @Kerry.

You need to change each element of the hash.keys in the string Instead, to change the hash.kiz in a string, and you should instead use it as long as everything that you want and whatever you do not want Need to play with rijks.

Let's look at your example first:

  str = "I have only one, two or maybe sixty" hash = {: one => 1 ,: 2 = & gt; 2 ,: six = & gt; 6,: sixty = & gt; 60}  

We may consider creating regex with each word before and after the word break ( \ b ):

  r0 = Regexp.union (hash.keys.map {| k | /\b#{k.to_s}\b/}) # = & gt; / (? - Mix: \ bone \ b). (? - Mix: \ btwo \ b). (? - Mix: \ bsix \ b). (? - Mix: \ bsixty \ b) / str.scan (r0) # = & gt; Without breaking the word,  scan   ["one", "two") will return.  str  in    , "two", "sixty"]  

, "six"] / Code> will match as "six" . (The word breaks are zero-width. A string before the string requires that the string be before a non-word character or string Must be at the beginning of the string. A string after string is required that the string is at the end of a non-word character or string.)

According to, the word break may not be sufficient or appropriate, for example (above hash ):

  str = "I have only one, two, one Or perhaps sixty " 

and we do not want to match the" twenty-one ", however,

  str.scan (R0) # = & gt; One option would be to use a regex that demands that whitespace or earlier than the matches are done in the beginning. ["One", "two", "one", "sixty" ]  

string, and white est After or after the end of the string should be:

  r1 = Regexp.union (hash.keys.map {| K | / (? & Lt; = ^ | \ S) # {k.to_s} (? = \ S | $) /}) str.scan (r1) # = & gt; ["Sixty"]  

(? & Lt; = ^ | \ s) is a positive eye ; (? = \ S | $) is an positive attitude

OK, which is "uniform" (good), but we now have the string "one" or < Do not match code> "two" (bad).

Perhaps the solution is to remove the first punctuation, which allows us to apply any of the above regexes:

  str.tr ('. ,?!:; - ',' ') # = & gt; "I can only have two twenty or sixty sixty" str.tr ('.,?!: -', ''). Scan (R) # = & gt; ["One", "two", "sixty"] str.tr ('.,!: -', ''). Scan (r1) # = & gt; ["One", "two", "sixty"]  

You may want to change / at the end of regex to / i

and 'A' is called upper case .


No comments:

Post a Comment