- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
我在这里遇到一个简单的 if else 链错误,我无法弄清楚发生了什么。前几天我开始学习 ruby,我已经了解一些 java,只是想重新编写程序以更快地学习 ruby。我正在尝试计算元音和辅音。不管怎样,这是我的代码...
#!/usr/bin/ruby/
alphabet = 'abcdefghijklmnopqrstuvwxyz'
array = alphabet.chars.to_a
vowel = 0
cons = 0
puts array.at(1)
for i 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 for loop
puts 'Vowel: ' + vowel.to_s
puts 'Consonants: ' + cons.to_s
这是我遇到的错误:
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]
我敢肯定这只是一些愚蠢的事情,但我一直在网上寻找帮助并且我听说过你们很棒的社区,所以我想我会在这里尝试,
可兰
最佳答案
Ruby 中没有++ 运算符。你应该使用 += 1
您可能还想了解 case
语句:
alphabet = 'abcdefghijklmnopqrstuvwxyz'
26.times do |i|
case alphabet[i]
when 'a' then vowel += 1
when 'e' then vowel += 1
when 'i' then vowel += 1
when 'o' then vowel += 1
when 'u' then vowel += 1
else cons += 1
end#end case
end#end times
puts 'Vowel: ' + vowel.to_s
puts 'Consonants: ' + cons.to_s
或者,更好的是,使用类 String
中的方法 count
,如下所示:
alphabet = 'abcdefghijklmnopqrstuvwxyz'
vowels = 'aeiou'
vowel_count = alphabet.count vowels
cons_count = alphabet.length - vowel_count
puts "Vowels: #{vowel_count}"
puts "Consonants: #{cons_count}"
关于Ruby -- If Elsif Else 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5957837/
我是一名优秀的程序员,十分优秀!