Howdy, Ive got some ruby code i need help with.... I have atm this Code: if token[1] =~ /(.*)/ return statement + "ERROR" unless token[2] =~ /[a-zA-Z|0-9]/ which is supposed to read - if token 1 contains anything, then return the statement + "Error" unless it contains a string or an integer... it doesnt seem to work, and ive tried a few things but dont know if the contains anything + the string or integer part is right? can anyone help?
What the code does does not match what it's suppose to read (or you're being too ambiguous). I would understand anything to be any object that isn't nil or false. Your control statement will always evaluate to false unless the element in token[1] is a string. The =~ method returns the index of the first character which matches your pattern. Given your pattern is to match anything, it will always return 0. 0 in Ruby is evaluated to be true in boolean context. Do you mean a string containing characters and numbers or literally a string or an integer? In the case of the former, your pattern should match only strings containing characters and numbers. If it's the latter, you should look at the is_a? and is_an_instance_of? methods. This is my understanding of what you're trying to do. Try it out in the IRb. Code: if token[1] and token[2].is_a?(String) or token[2].is_a?(Integer) return statement + 'ERROR' end if token[1] is a shortcut for if not token[1].nil?. Remember, everything in Ruby evaluates to true in boolean context if it's not nil or false. Lastly, remember that the first element in a collection will have the index of 0. Finally, you should be careful storing different types of objects in a collection. While it's perfectly valid, it means you always need to check the type before invoking methods on it.
ok, i need to match a string which has ' ' either side. something like Code: return "ERROR" unless token [1] == /^ \'[a-zA-Z]+\' $/ should read return "ERROR" unless token 1 is equal (do i use is equal here?) to '<string>' or if the string uses a letter number combo would be [a-zA-Z0-9] ? like 'abcd123' im not sure on how to get it to match any string so long as it is surrounded by ' ' anyone?
You ought to take a look at the API documentation on the String class. In particular, the match() method. Rubular is a Ruby regular expression editor and tester in your browser, perfect for trying out your patterns. You'll probably want something like Code: \A'.*'\Z