7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ruby のあまり知られていない?機能(初心者向け)

Last updated at Posted at 2014-08-02

はじめに

Ruby を勉強していく過程で私が学んだ、あまり知られていないだろう機能等を紹介する記事です。
使用した Ruby のバージョンは 2.1.1p76 、 pry のバージョンは 0.10.0 on Ruby 2.1.1
「他にもこんな書き方あるよ」などありましたら、教えていただけると嬉しいです。

nonzero? の戻り値

zero?true / false を返すが、nonzero?self / nil を返すみたい。true / false を返した方が分かりやすいと思うのだが。。。

[1] pry(main)> 1.nonzero?
=> 1
[2] pry(main)> 0.nonzero?
=> nil

Array → Hash

Array を Hash に変換する方法。いろいろとやり方があるみたい。

まずはよく使う方法。

[1] pry(main)> array = [["a", 1], ["b", 2], ["c", 3]]
=> [["a", 1], ["b", 2], ["c", 3]]
[2] pry(main)> hash = Hash[array]
=> {"a"=>1, "b"=>2, "c"=>3}

続いて zip を使う方法。

[3] pry(main)> keys = %w(a b c)
=> ["a", "b", "c"]
[4] pry(main)> values = [ 1, 2, 3 ]
=> [1, 2, 3]
[5] pry(main)> keys.zip(values).to_h
=> {"a"=>1, "b"=>2, "c"=>3}

最後に transpose を使う方法。

[6] pry(main)> [ keys, values ].transpose.to_h
=> {"a"=>1, "b"=>2, "c"=>3}

ziptranspose を使った方法の違いは、 zip は配列(今回のサンプルでは keysvalues )の要素数が違った場合でも動作するが、 transpose はエラーとなる 点。他にも違いがあるのかもしれないが、よくわからない。

[7] pry(main)> keys = %w(a b)
=> ["a", "b"]
[8] pry(main)> keys.zip(values).to_h
=> {"a"=>1, "b"=>2}
[9] pry(main)> [ keys, values ].transpose.to_h
IndexError: element size differs (3 should be 2)
from (pry):7:in `transpose'

symbol → proc

ブロックの使用を避ける方法。
あまり見たことがない書き方だが、実際に使用するシーンはあるのだろうか。

[1] pry(main)> (1..5).each { |x| puts x }
1
2
3
4
5
=> 1..5
[2] pry(main)> (1..5).each &method(:puts)
1
2
3
4
5
=> 1..5

配列要素の結合

join を使うのが一般的だと思うけど、 join を使わない方法もあるみたい。

[1] pry(main)> a = %w(This is a sample code)
=> ["This", "is", "a", "sample", "code"]
[2] pry(main)> a.join(', ')
=> "This, is, a, sample, code"
[3] pry(main)> a * ', '
=> "This, is, a, sample, code"

Array#* の使用はおすすめではない模様。

7
6
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?