Stringクラスにオープンクラスを使って(この表現は正しい?)、新しいメソッドを追加したいのですが、!メソッドを作るにはどのようにかけば良いんでしょうか?
Ruby
1def nextChar (c) 2 case c 3 when 'z' 4 ret = 'a' 5 when 'Z' 6 ret = 'A' 7 when ' ','.',',','?','!','_','{','}' 8 ret = c 9 else 10 ret = c.next 11 end 12 return ret 13end 14 15class String 16 def caesar (n) 17 res = String.new 18 self.chars.map{|c| 19 n.times do 20 c = nextChar c 21 end 22 res += c 23 } 24 return res 25 end 26 27 def caesar!(n) 28 res = String.new 29 self.chars.map{|c| 30 n.times do 31 c = nextChar c 32 end 33 res += c 34 } 35 self = res 36 return self 37 end 38end
とりあえず適当に書いてみたのですが案の定
Ruby
1self = res
のところで
Error
1Can't change the value of self
と言われてしまいます。
あと、もし質問に関係ないと怒られてしまったら質問し直すのですが、
Rubyの標準ライブラリのソースコードはどうすれば見られますか?
最初は適当なメソッドのソースコードを読んでみて、書き方を知ろうと思ったのですが、わからなくて質問することにしました。
環境はCentOS7です。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/09/01 08:43