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??
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??
I explain with an example:
class MyTime
attr_accessor :hours, :minutes
def initialize
…
…
end
…other methods…
end
Now, without the setter methods for hours (or minutes) i can assign a
totally inconsistent value like this:
t = MyTime.new
t.minutes = 75 # that make no sense at all!
when with a setter method i can control the input like this:
#that’s only an example…i know that this method is
#totally bad!
def minutes=(value)
if value > 60
gap = value - 60
minutes = gap
hours = hours + 1
else
minutes = value
end
end
How can i avoid this inconsistency without a setter method
implementation?? attr_accessor is useless in this case? (it’s so
convenient!! (-: )
I hope that my questions are clear, sorry for my poor english!
If you have some links that talk about this topics, please tell me!
Thanks a lot!
caligari.