問題の解答例を実行するとエラーが出ることと、解答例で意味がよくわからないところがあるのでご教授願いたいです。
まず問題です。
lang
1# Write a method that takes an array of numbers in. Your method should 2# return the third greatest number in the array. You may assume that 3# the array has at least three numbers in it.
そして、それの解答例です。
lang
1def third_greatest(nums) 2 first = nil 3 second = nil 4 third = nil 5 6 idx = 0 7 while idx < nums.length 8 value = nums[idx] 9 if first == nil || value > first 10 third = second 11 second = first 12 first = value 13 elsif second == nil || value > second 14 third = second 15 second = value 16 elsif third == nil || value > third 17 third = value 18 end 19 20 idx += 1 21 end 22 23 return third 24end
これを使って以下のことを実行するとコードが間違いがなければ、3つ"true"と返ってきます。
lang
1# These are tests to check that your code is working. After writing 2# your solution, they should all print true. 3 4puts( 5 'third_greatest([5, 3, 7]) == 3: ' + 6 (third_greatest([5, 3, 7]) == 3).to_s 7) 8puts( 9 'third_greatest([5, 3, 7, 4]) == 4: ' + 10 (third_greatest([5, 3, 7, 4]) == 4).to_s 11) 12puts( 13 'third_greatest([2, 3, 7, 4]) == 3: ' + 14 (third_greatest([2, 3, 7, 4]) == 3).to_s 15)
しかしこれを実際実行すると、
lang
110-third-greatest.rb:19: syntax error, unexpected keyword_elsif, expecting keyword_end 2 elsif second == nil || value > second 3 ^ 410-third-greatest.rb:22: syntax error, unexpected keyword_elsif, expecting keyword_end 5 elsif third == nil || value > third 6 ^ 710-third-greatest.rb:30: syntax error, unexpected keyword_end, expecting end-of-input 8```‘ 9のようにエラーが出てきます。質問が3つあります。 10 111.エラーが出るのは解答例に不備があると思うのですが、見つけられませんでした。どうか不備を教えてください。 12 132.最初のコードの 14```lang-言語名 15first = nil 16second = nil 17third = nil
の意味がわかりません。ご教授願います。
3.if文
lang
1if first == nil || value > first 2 third = second 3 second = first 4 first = value 5 elsif second == nil || value > second 6 third = second 7 second = value 8 elsif third == nil || value > third 9 third = value 10 end
がわかりません。一体何をしているのでしょうか。。。の
回答とは関係ありませんが、Rubyのプログラムについての質問なので、タグはRubyにしたほうが、Rubyに詳しい回答者の方々に回答していただきやすくなります。
回答5件
あなたの回答
tips
プレビュー