Rubyをベースにプログラミングを学んでいる超初心者です!初めての'ord'、'ASCll'、'char'などが出てきて正直コードの意図と意味がよくわかりません。。。以下が問題とその解答となるコードです。一応自分自身の解釈をコードの横に書いておきます。
Ruby
1# Write a method that takes in an integer `offset` and a string. 2# Produce a new string, where each letter is shifted by `offset`. You 3# may assume that the string contains only lowercase letters and 4# spaces. 5# 6# When shifting "z" by three letters, wrap around to the front of the 7# alphabet to produce the letter "c". 8# 9# You'll want to use String's `ord` method and Integer's `chr` method. 10# `ord` converts a letter to an ASCII number code. `chr` converts an 11# ASCII number code to a letter. 12 13def caesar_cipher(offset, string) #caesar_cipher( , )というメソッドを定義する 14 words = string.split(" ") #wordsにstringを文字列で分割したものを代入する 15 16 word_idx = 0 #word_idxに0を代入する 17 while word_idx < words.length #「word_idx < wordsの文字列数」の間繰り返す 18 word = words[word_idx] #wordにword_idx番目の文字列を代入 19 20 letter_idx = 0 #letter_idxに0を代入 21 while letter_idx < word.length #「letter_idx < wordの文字数」の間繰り返す 22 char_i = word[letter_idx].ord - "a".ord #文字'word[letter_idx]'に対応する数字(ASCllコード) - 'a'に対応する数字(ASCllコード)をchar_iに代入??? 23 24 new_char_i = (char_i + offset) % 26 #new_char_iに(char_i + offset) % 26を代入??? 25 word[letter_idx] = ("a".ord + new_char_i).chr #word[letter_idx]に('a'のASCllコード + new_char_i)に対応する文字を代入 26 27 letter_idx += 1 #letter_idxを1足してwhile letter_idx < word.lengthに戻る 28 end #終わり 29 30 word_idx += 1 #word_idxに1足してwhile word_idx < words.lengthに戻る 31 end #終わり 32 33 return words.join(" ") #wordsを連結し???、返す 34end 35 36# These are tests to check that your code is working. After writing 37# your solution, they should all print true. 38 39puts( 40 'caesar_cipher(3, "abc") == "def": ' + 41 (caesar_cipher(3, 'abc') == 'def').to_s 42) 43puts( 44 'caesar_cipher(3, "abc xyz") == "def abc": ' + 45 (caesar_cipher(3, 'abc xyz') == 'def abc').to_s 46) 47
???とついているものが分からない部分ですが、全体的にわかっていません。。。メソッドについては
- .ord:その文字に対応するASCllコードに変換
- .chr:そのASCllコードに対応する文字に変換
- char:文字列中の文字を繰り返し取り出す???
と認識しています。
???と全体的なコードの意図・意味をご教授願います!
また余談ですが、caesar_cipher(offset, string)
の
- caesar(皇帝)
- cipher(ゼロ)
- offset(差し引き)
のプログラミングに置ける意味も教えていただけたら幸いです。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2015/11/14 09:42