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
···
--
Posted via http://www.ruby-forum.com/.
Flaab Mrlinux wrote:
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
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:
1. You shouldn't use instance variables when local ones will suffice.
I.e. use "variantes" and "cont" instead of "@variantes" and "@cont"
2. Please send code snippets with identifiers in English - it takes a
little guesswork out of what you're trying to achieve.
3. 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 Vallner
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
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
Matthew Moss 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
···
--
Posted via http://www.ruby-forum.com/\.