From: Mark Hubbart Date: 2004-02-05T09:08:20+09:00 Subject: Re: two questions On Feb 4, 2004, at 3:50 PM, caligari wrote: > Hi all, i'm new to ruby and i find it very exciting, but i've two > little question that i cannot find answers for. > > First: how can i use a variable name within a regex? In other words, i > explain it with some perl code: > > #begin > use strict; > > print "give me a string: "; > chomp (my $str = ); > > #that's the italian version of mary poppin's > #saying (-: > my $line = "supercalifragilistichespiralidoso"; > print "$1\n" if $line =~ /($str)\w+/; > #end > > Now, as you can see from this stupid code, if i enter "super" as $str, > it prints out "super". > But because i've to use the construct #{...} to interpolate a variable > (in ruby), how can i use the trick?? Interpolating is done the same way, it doesn't matter whether you are using strings or regexen. just enclose your variable in #{..} and stick it where you want it. Here's how it would go in your example: #that's the italian version of mary poppin's #saying (-: my $line = "supercalifragilistichespiralidoso"; print "$1\n" if $line =~ /(#{$str})\w+/; #end > Second: this is a question on the object orientation consistency of > ruby (i'm not doubt that ruby is consistent, but i'm only a newbie > that search for answers...). > If i declare an instance variale as attr_accessor, i can avoid to > write getter/setter methods, but how can i surely give a value to a > variable without writing the relative method?? Well... No. The only way you can check the validity of the data being set by the setter is to write your own setter method. Cheers, Mark