Rubyをベースにプログラミングを学んでいる超初心者です。課題に対する解答のコードで自分自身が認識している意味があっているのか確認して欲しいです。
問題は、小文字と空白で構成されている文ある。その単語それぞれの頭文字を大文字に変えるメソッドを書け、です。①が確認したいところで、②が質問です。
Ruby
1# Write a method that takes in a string of lowercase letters and 2# spaces, producing a new string that capitalizes the first letter of 3# each word. 4# 5# You'll want to use the `split` and `join` methods. Also, the String 6# method `upcase`, which converts a string to all upper case will be 7# helpful. 8 9 10def capitalize_words(string) 11 words = string.split(" ") 12 13 i = 0 14 while i < words.length #iがsplitで分けられた単語の数より小さい場合以下を繰り返す・・・① 15 word = words[i] 16 word[0] = word[0].upcase 17 18 i += 1 19 end 20 21 return words.join(" ") 22end 23 24# These are tests to check that your code is working. After writing 25# your solution, they should all print true. 26 27puts( 28 'capitalize_words("this is a sentence") == "This Is A Sentence": ' + 29 (capitalize_words("this is a sentence") == "This Is A Sentence").to_s #ここのto_sの意味・・・② 30) 31puts( 32 'capitalize_words("mike bloomfield") == "Mike Bloomfield": ' + 33 (capitalize_words("mike bloomfield") == "Mike Bloomfield").to_s 34)
実行すると
lang
1apitalize_words("this is a sentence") == "This Is A Sentence": true 2capitalize_words("mike bloomfield") == "Mike Bloomfield": true
になります。
①、このwords.lengthとは単語数ですよね?つまり"this is a sentence"の場合は"4"なるということです。
②、ここにおけるto_sメソッドのイマイチ役割がわかりません。"puts"の場合、数字の比較ならto_sをつけて文字化するのも理解できますが、もともと文字の場合to_sメソッドをつける意味がよくわかりません。ただ、付けなければエラーが出ました。
lang
1p ( "abcd" == "abcd" )
を実行すると"true"と返ってきます。"p"メソッドに変えた場合でもto_sを無くすとエラーが出ます。
このto_sの役割をご教授願います。。。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2015/10/31 06:54