落書きノート

ふと自分が気になった事を書いてます

Ruby資格技術者問題集

今回はスレッド、ファイバ、next、redo、例外処理です。こんな感じになりました。

irb(main):001:0> t = Thread.new do
irb(main):002:1* p "start"
irb(main):003:1> sleep 5
irb(main):004:1> p "end"
irb(main):005:1> end
"start"
=> #<Thread:0x007feb0a988a58@(irb):1 sleep>
irb(main):006:0> p "wait"
"wait"
=> "wait"
irb(main):007:0> "end"
irb(main):010:0> t.join
=> #<Thread:0x007feb0a988a58@(irb):1 dead>
irb(main):011:0> 3.times do |i|
irb(main):012:1* Thread.start(i) do |index|
irb(main):013:2* p "thread-#{index} start"
irb(main):014:2> end
irb(main):015:1> end
"thread-2 start"
"thread-1 start"
thread-0 start"
=> 3
irb(main):016:0> 3.times do |i|
irb(main):017:1* puts i
irb(main):018:1> end
0
1
2
=> 3
irb(main):019:0> f = Fiber.new do
irb(main):020:1* (1..3).each do |i|
irb(main):021:2* Fiber.yield i
irb(main):022:2> end
irb(main):023:1> nil
irb(main):024:1> end
=> #<Fiber:0x007feb0b867718>
irb(main):025:0> p f.resume
1
=> 1
irb(main):026:0> p f.resume
2
=> 2
irb(main):027:0> p f.resume
3
=> 3
irb(main):028:0> p f.resume
nil
=> nil
irb(main):029:0> p f.resume
FiberError: dead fiber called
  from (irb):29:in `resume'
  from (irb):29
  from /Users/hirotoshi/.rbenv/versions/2.2.2/bin/irb:11:in `<main>'
irb(main):030:0> 10.times do |i|
irb(main):031:1* next if i == 5
irb(main):032:1> print i, " "
irb(main):033:1> end
0 1 2 3 4 6 7 8 9 => 10
irb(main):034:0> 10.times do |i|
irb(main):035:1* redo if i == 5
irb(main):036:1> print i, " "
irb(main):037:1> end
0 1 2 3 4 ^CIRB::Abort: abort then interrupt!
  from (irb):35:in `call'
  from (irb):35:in `block in irb_binding'
  from (irb):34:in `times'
  from (irb):34
  from /Users/hirotoshi/.rbenv/versions/2.2.2/bin/irb:11:in `<main>'
irb(main):042:0> raise ArgumentError, "引数が不正です"
ArgumentError: 引数が不正です
  from (irb):42
  from /Users/hirotoshi/.rbenv/versions/2.2.2/bin/irb:11:in `<main>'
irb(main):043:0> raise ArgumentError.new, "引数が不正です"
ArgumentError: 引数が不正です
  from (irb):43
  from /Users/hirotoshi/.rbenv/versions/2.2.2/bin/irb:11:in `<main>'
irb(main):044:0> err = ArgumentError.new("引数が不正です")
=> #<ArgumentError: 引数が不正です>
irb(main):045:0> raise err
ArgumentError: 引数が不正です
  from (irb):45
  from /Users/hirotoshi/.rbenv/versions/2.2.2/bin/irb:11:in `<main>'
irb(main):046:0> raise "実行中にエラーが発生しました"
RuntimeError: 実行中にエラーが発生しました
  from (irb):46
  from /Users/hirotoshi/.rbenv/versions/2.2.2/bin/irb:11:in `<main>'
irb(main):047:0> begin
irb(main):048:1* 1 / 0
irb(main):049:1> p 1
irb(main):050:1> rescue
irb(main):051:1> p 0
irb(main):052:1> end
0
=> 0
irb(main):053:0> begin
irb(main):054:1* p 1
irb(main):055:1> rescue
irb(main):056:1> p 0
irb(main):057:1> else
irb(main):058:1* p 2
irb(main):059:1> ensure
irb(main):060:1* p 3
irb(main):061:1> end
1
2
3
=> 2
irb(main):062:0> 1 / 0 rescue p 1
1
=> 1
irb(main):063:0> def foo
irb(main):064:1> -1 / 0
irb(main):065:1> rescue
irb(main):066:1> p 1
irb(main):067:1> end
=> :foo
irb(main):068:0> foo
1
=> 1