2014-03-01から1ヶ月間の記事一覧
勉強がてら書いてみる。 def collatz count = 0 func = Proc.new do |n| if n == 1 then count else count += 1 if n.even? then func.call(n / 2) else func.call(n * 3 + 1) end end end end (2..10000).each do |i| puts collatz.call(i) end 恥ずかしな…
業務向けWebアプリでは、オペレータさんがマウスを使わずキーボードのみで操作しているかと思います。この場合、Enterキー押下でsubmitするケースが多いのではないでしょうか。このあたりのUIを作っていて、Enterキー押下時の動きがよくわからずにハマってし…
throw-catchで大域脱出ができるらしい。 # coding: utf-8 str = catch :escape do loop do puts "ループ1" loop do puts "ループ2" throw :escape, "脱出" end end end puts str 実行結果は以下のとおり。 $ ruby throw-catch.rb ループ1 ループ2 脱出
OptionParserってのを使うと簡単らしいです。 # coding: utf-8 require 'optparse' def cmdline args = {} OptionParser.new do |parser| parser.on('-f', '--foo', '真偽値オプション') {|v| args[:foo] = v} parser.on('-b VALUE', '--bar VALUE', '引数付…
クラス変数は継承される。 クラスインスタンス変数は継承されない。 # coding: utf-8 class Foo # クラス変数 @@var1 = 123 # クラスインスタンス変数 @var2 = 456 def self.var1 @@var1 end def self.var2 @var2 end end class Bar < Foo end p Foo.var1 p …
以下の手順で。 開始行に移動し「mb」 終了行に移動し「me」 「:'b,'ey」<Enter>と実行 解説(というか、理屈を自分で忘れないように。。) 「m」はマークをつけるコマンドです。その次の文字がマーク。 マークは任意の文字で良いですが、beginとendのつもり。 最後に</enter>…
# coding: utf-8 class Foo def hello puts "hello" end end # クラスオブジェクトを変数に代入 a = Foo obj = a.new obj.hello 実行結果は helloです。
上から順に探索される。 1. 特異メソッド 2. そのクラスで定義したメソッド 3. includeしたmoduleで定義したメソッド 4. スーパークラスで定義したメソッド
Javaのprivateメソッドは「自クラス内でしか呼び出しができないメソッド」ですが、Rubyでは「レシーバを付けた呼び出しができないメソッド」です。あくまでそれだけです。自クラス外からも呼び出しができます。 # coding: utf-8 class SuperClass private de…
Rubyのexit関数はSystemExit例外を投げます。 begin exit rescue StandardError puts $!.class rescue SystemExit puts $!.class ensure puts "ensure" end puts "end" 実行結果は以下のとおり。 SystemExit ensure end
class Super @@x = 1 def self.x @@x end end class Sub < Super @@x = 2 end p Super.x 実行結果は以下のとおり。 2
こんなこともできるんですね。 class Foo end class Bar def Foo.foo puts "foo defined in Bar" end end Foo.foo 実行すると $ ruby other_class.rb foo defined in Bar