borderline borderline - 1 month ago 8
Ruby Question

Dynamic condition in ruby on rails

I have the following condition:

if "FIX_STRING 0,0,DYNAMIC_STRING" == "FIX_STRING #{integer_from_0_to_5},#{integer_from_0_to_5},#{DYNAMIC_STRING}"
true
else
false
end


How to make it dynamically like this?

if "FIX_STRING 0,0,DYNAMIC_STRING" == "FIX_STRING #{/0|1|2|3|4|5/},#{/0|1|2|3|4|5/},#{/A|B|C|D/}"
true
else
false
end

Answer

You're on the right track here, but you've got a very peculiar coding style. The first thing to point out is that a comparison like == already returns a boolean value of true or false, there's no reason for the if which then returns exactly the same thing.

The second thing is that you're comparing a string to another string, so they have to match exactly. Close enough does not count. If you evaluate your other string you get a mess:

"FIX_STRING (?-mix:0|1|2|3|4|5),(?-mix:0|1|2|3|4|5),(?-mix:A|B|C|D)" 

Finally, if you're trying to test a string versus a regular expression, you do this:

PATTERN = /\AFIX_STRING [0-5],[0-5],[A-D]\z/

You can test this sort of thing on Rubular to get it right. Here [0-5] means anything in that range. It's short-hand for what you had.

Then you can test arbitrary strings versus this pattern:

"FIX_STRING 3,4,D".match(PATTERN)
# => #<MatchData "FIX_STRING 3,4,D">

So that matched.

Newer versions of Ruby have a match? method that only tests matches, it doesn't return what matched, which you might want to make use of if you're running on 2.3 or later. It's faster than the plain match method, though that only really matters if you're doing a lot of matches inside loops.

Comments