Hatena::Groupruby

mrのRuby学習帳 このページをアンテナに追加 RSSフィード

2009-09-26

arrayの+メソッド arrayの+メソッド - mrのRuby学習帳 を含むブックマーク

irb(main):001:0> a = [1,2,3]
=> [1, 2, 3]
irb(main):002:0> b = ["a","b","c"]
=> ["a", "b", "c"]
irb(main):003:0> c = a + b
=> [1, 2, 3, "a", "b", "c"]
irb(main):004:0>

arrayのcollectメソッド(p117) arrayのcollectメソッド(p117) - mrのRuby学習帳 を含むブックマーク

irb(main):001:0> a = [1,2,3]
=> [1, 2, 3]
irb(main):002:0> a.collect {|x| x + 1}
=> [2, 3, 4]
irb(main):003:0> p a
[1, 2, 3]
=> nil

リファレンスを見ると、collectはarrayにMix-inされているenumerableモジュールのメソッドみたいです。

arrayのcompactメソッド arrayのcompactメソッド - mrのRuby学習帳 を含むブックマーク

irb(main):001:0> a = ["a",nil,"c"]
=> ["a", nil, "c"]
irb(main):002:0> a.compact
=> ["a", "c"]
irb(main):003:0> p a
["a", nil, "c"]
=> nil

arrayのconcatメソッド arrayのconcatメソッド - mrのRuby学習帳 を含むブックマーク

irb(main):001:0> a = [1,2,3]
=> [1, 2, 3]
irb(main):002:0> b = ["a","b","c"]
=> ["a", "b", "c"]
irb(main):003:0> a.concat
ArgumentError: wrong number of arguments (0 for 1)
        from (irb):3:in `concat'
        from (irb):3
irb(main):004:0> a.concat(b)
=> [1, 2, 3, "a", "b", "c"]
irb(main):005:0> p a
[1, 2, 3, "a", "b", "c"]
=> nil
irb(main):006:0>

arrayのdetectメソッド arrayのdetectメソッド - mrのRuby学習帳 を含むブックマーク

irb(main):001:0> a = ["a","b","c","a","b","c"]
=> ["a", "b", "c", "a", "b", "c"]
irb(main):002:0> a.detect("b")
LocalJumpError: no block given
        from (irb):2:in `detect'
        from (irb):2:in `each'
        from (irb):2:in `detect'
        from (irb):2
irb(main):003:0> a.detect{|x| x = "b"}
=> "a"
irb(main):004:0> a.detect{|x| x = "c"}
=> "a"
irb(main):005:0> a.detect{|x| x == "c"}
=> "c"

比較は==だった。

arrayのfillメソッド arrayのfillメソッド - mrのRuby学習帳 を含むブックマーク

irb(main):001:0> a = Array.new
=> []
irb(main):002:0> a.fill
ArgumentError: wrong number of arguments (0 for 1)
        from (irb):2:in `fill'
        from (irb):2
irb(main):003:0> a.fill("test")
=> []
irb(main):004:0> a.fill("test")
=> []
irb(main):005:0> a = [1,2,3]
=> [1, 2, 3]
irb(main):006:0> a.fill("test")
=> ["test", "test", "test"]