2007-08-01から1ヶ月間の記事一覧

ruby学習メモ 練習問題

CodeZine「脱 超初心者 Javaアルゴリズム問題集 第2回」を ruby でやってみる http://codezine.jp/careerup/article/aid/1495.aspx 問題1 標準入力された月、日が、今日であるかどうかを判定するプログラムを作成してください。 コマンドラインに「今日は何…

ruby学習メモ 変数

num = 81 => 81 6.times do puts "#{num.class}: #{num}" num *= num end Fixnum: 81 Fixnum: 6561 Fixnum: 43046721 Bignum: 1853020188851841 Bignum: 3433683820292512484657849089281 Bignum: 11790184577738583171520872861412518665678211592275841109…

ruby学習メモ 練習問題

CodeZine「脱 超初心者 Javaアルゴリズム問題集 第1回」を ruby でやってみる http://codezine.jp/careerup/article/aid/1426.aspx 問題1 標準入力された値があればそのまま表示、値がなければエラーメッセージを表示するプログラムを作成してください。 な…

ruby学習メモ

クロージャブロック class TestClass def name @name end def initialize(label, &action) @name = label @action = action end def call_action puts "start call_action" @action.call(self) end end テスト1 test1 = TestClass.new("test") { name } tes…

ruby学習メモ

イテレータ each irb(main):006:0> [ 1,2,3,4,5].each {|i| puts i} 1 2 3 4 5 => [1, 2, 3, 4, 5] collect 配列を作成してくれる irb(main):008:0* [ 1,2,3,4,5].collect {|i| puts i ; i + 1 } 1 2 3 4 5 => [2, 3, 4, 5, 6] ファイル内容出力 f = File.op…

ruby学習メモ

オブジェクトの凍結(#freeze) test1 = "string" test2 = test1 test1.freeze # 凍結 test2[0] = "A" test1が参照する文字列は凍結されているので TypeError が発生する TypeError: can't modify frozen string from (irb):33:in `[]=' from (irb):33 from :0…

ruby学習メモ

ブロックを利用したファイルのオープン、読み込み、クローズ # ファイルをオープンしてクローズする class File def File.open_and_process(*args) f = File.open(*args) yield f f.close end end File.open_and_process("testfile.txt", "r") do |file| # f…

ruby学習メモ アクセス制御

class TestClass def defaultMethod # public return "default -> public" end protected def protectedMethod # protected return "protected" end private def privateMethod # private return "private" end public def publicMethod # public return "pu…

ruby学習メモ Singleton

コンストラクタの private 化とインスタンスの Singleton 化 class MyClass # new をプライベート化することにより、コンストラクタによるインスタンス化 # が出来ないようにする private_class_method :new #インスタンスを保持するクラス変数 @@singleton …

ruby学習メモ インスタンスメソッドとクラスメソッド

class Example /** インスタンスメソッド */ def instance_method return "instance method" end /** クラスメソッド */ def Example.class_method return "class method" end end irb(main):012:0* Example.class_method => "class method" irb(main):013:0…