if statement - Ruby -- If Elsif Else Error -
i'm getting error here simple if else chain, , can't figure out going on. started learning ruby other day, know java, , trying re-write programs learn ruby faster. trying tally vowels , consonants. anyways here code...
#!/usr/bin/ruby/ alphabet = 'abcdefghijklmnopqrstuvwxyz' array = alphabet.chars.to_a vowel = 0 cons = 0 puts array.at(1) in 0...26 if array.at(i) == "a" vowel++ elsif array.at(i) == 'e' vowel++ elsif array.at(i) == 'i' vowel++ elsif array.at(i) == 'o' vowel++ elsif array.at(i) == 'u' vowel++ else cons++ end#end if else chain end#end loop puts 'vowel: ' + vowel.to_s puts 'consonants: ' + cons.to_s
here error getting:
c:/users/kelan/documents/programming/ruby files/little programs/alphabet.rb:11: syntax error, unexpected keyword_elsif elsif array.at(i) == 'e' ^
c:/users/kelan/documents/programming/ruby files/little programs/alphabet.rb:13: syntax error, unexpected keyword_elsif elsif array.at(i) == 'i' ^
c:/users/kelan/documents/programming/ruby files/little programs/alphabet.rb:15: syntax error, unexpected keyword_elsif elsif array.at(i) == 'o' ^
c:/users/kelan/documents/programming/ruby files/little programs/alphabet.rb:17: syntax error, unexpected keyword_elsif elsif array.at(i) == 'u' ^
c:/users/kelan/documents/programming/ruby files/little programs/alphabet.rb:19: syntax error, unexpected keyword_else
c:/users/kelan/documents/programming/ruby files/little programs/alphabet.rb:21: syntax error, unexpected keyword_end
c:/users/kelan/documents/programming/ruby files/little programs/alphabet.rb:25: syntax error, unexpected $end, expecting keyword_end puts 'consonants: ' + cons.to_s ^
[finished in 0.203 seconds]
i'm sure it's silly, i've been looking forever online , have heard of great community, thought try here,
kelan
there no ++ operator in ruby. should have used += 1
may want learn case
statement:
alphabet = 'abcdefghijklmnopqrstuvwxyz' 26.times |i| case alphabet[i] when 'a' vowel += 1 when 'e' vowel += 1 when 'i' vowel += 1 when 'o' vowel += 1 when 'u' vowel += 1 else cons += 1 end#end case end#end times puts 'vowel: ' + vowel.to_s puts 'consonants: ' + cons.to_s
or, better, use method count
class string
, this:
alphabet = 'abcdefghijklmnopqrstuvwxyz' vowels = 'aeiou' vowel_count = alphabet.count vowels cons_count = alphabet.length - vowel_count puts "vowels: #{vowel_count}" puts "consonants: #{cons_count}"
Comments
Post a Comment