Rubyをベースにプログラミングを学んでいる超初心者です。ある課題の解答が理解できなくて苦しんでいます。まず自分自身の認識を#の後に書きます。??が入っているところがわからないところです。
Ruby
1# Write a method that takes in a number and returns a string, placing 2# a single dash before and after each odd digit. There is one 3# exception: don't start or end the string with a dash. 4# 5# You may wish to use the `%` modulo operation; you can see if a number 6# is even if it has zero remainder when divided by two. 7# 8# Difficulty: medium. 9 10def dasherize_number(num) 11 num_s = num.to_s **#num_sを文字化する??・・・①** 12 result = "" **#resultという変数を作る??・・・②** 13 14 idx = 0 #idxが文字の長さより短い間以下を繰り返す。 15 while idx < num_s.length 16 digit = num_s[idx].to_i #digitにidx番目の文字を数字化して代入する 17 18 if idx > 0 19 pre_digit = num_s[idx - 1].to_i #もしidxが0より大きい場合、pre_digitにidx-1番目の文字を数字化して代入する 20 21 if (pre_digit % 2 == 1) || (digit % 2 == 1) #もしpre_digit,digitが奇数だった場合 22 result += "-" #resultに-を代入する 23 end 24 25 end #一つ目のifを終わる 26 result += num_s[idx] #resultにidx番目の文字を代入する 27 28 idx += 1 #次の文字を検証する 29 end 30 31 return result 32 33end
それでは質問させていただきます。
①
なぜnum_sというものを使わなければならないのでしょうか。実際numで実行してみたところうまくいきませんでした。
②
result = の後の""はどういった意味があるのでしょうか。
以上の二つが調べても理解ができなかったのでご教授願います。
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2015/10/30 06:35