flaab
November 17, 2006, 2:56pm
1
Hi all!!
I’ve declared a method inside the string class that has to answer the
amount of “X” and “2” chars in a string. The string is ALWAYS gonna be
15 chars size. The code is the following:
class String
# DAME VARIANTES
def variantes
@variantes = 0
15.times do |@cont|
if (self[@cont] == "2" || self[@cont] == "X")
@variantes = @variantes + 1
end
end
return @variantes
end
end
cadena = “XX222XX222XX1X2”
puts cadena.variantes
And the last line ALWAYS ANSWERS a CERO. Why? Why it doesn’t enter the
if statement inside the method?
Thx
flaab
November 17, 2006, 3:26pm
2
Flaab M. wrote:
@variantes = 0
cadena = “XX222XX222XX1X2”
puts cadena.variantes
And the last line ALWAYS ANSWERS a CERO. Why? Why it doesn’t enter the
if statement inside the method?
Thx
String#[] returns the integer code of the character at that position.
So, either use
if(self[@cont] == ?2 || self[@cont] == ?X)
or
if(self[@cont …@cont ] == “2” || self[@cont …@cont ] == “X”)
Also:
You shouldn’t use instance variables when local ones will suffice.
I.e. use “variantes” and “cont” instead of “@variantes ” and “@cont ”
Please send code snippets with identifiers in English - it takes a
little guesswork out of what you’re trying to achieve.
Smileys and netspeak are fluff and a little out of place for the
medium. Cut out the “xD” and use “Thanks” instead of Thx, please.
David V.
flaab
November 17, 2006, 3:32pm
3
Check the manual
str[0] will return a numeric representation of the character
what You need is str[0,1] one character starting from the first
position.
Try this:
class String
def variantes
@variantes = 0
Range.new(0, 14).each { |i|
if (self[i,1] == “2” || self[i,1] == “X”)
@variantes = @variantes + 1
end
}
return @variantes
end
end
str = “XXXXX22222XXXXX”
puts str.variantes
Dmitry
flaab
November 17, 2006, 4:00pm
4
Now that you got a couple answers why your comparisons didn’t work,
time to suggest a better method.
class String
def variantes
count “2X”
end
end
flaab
November 17, 2006, 7:11pm
5
Matthew M. wrote:
Now that you got a couple answers why your comparisons didn’t work,
time to suggest a better method.
class String
def variantes
count “2X”
end
end
Wow THANKS i´m amazed… =D That’s pretty better!
I’m newbie at ruby didn’t know it had such a simple way to do this.
Thanks a lot
flaab
November 17, 2006, 7:31pm
6
Hi –
On Fri, 17 Nov 2006, David V. wrote:
Smileys and netspeak are fluff and a little out of place for the
medium. Cut out the “xD” and use “Thanks” instead of Thx, please.
Oh, I think we do OK despite the occasional smiley Let’s err on
the side of making people feel welcome unless they do something
clearly troll-like.
Thx –
David