LoginSignup
7
3

More than 3 years have passed since last update.

(Ryby)to_○メソッドの種類と処理をまとめてみました

Posted at

to_○メソッドの種類と処理内容をAからまとめてみました

範囲オブジェクト・ハッシュを配列に変換

to_a

(1..5).to_a => [1,2,3,4,5]
(a..e).to_a => [a,b,c,d,e]

currencies = {japan: "yen" , us: "dollar" , india: "rupee"}
currencies.to_a  
=>[[:japan,yen],[:us,dollar],[:india,rupee]]

文字数を複素数に変換

複素数とは

to_c 

"0.3-0.5i".to_c
=>(0.3-0.5i)

整数を少数に変換

to_f

10.to_f =>10.0
10.to_f / 4  => 2.5 

配列をハッシュに変換

to_h

arry = [[:japan,yen],[:us,dollar],[:india,rupee]]
arry.to_h
=>{japan: "yen" , us: "dollar" , india: "rupee"}

文字列を数値に変換

to_i

10 + "3"  =>  103
10 + "3".to_i  => 13

文字列を有理数に変換

to_r

"3/2".to_f
=> (3/2)

オブジェクトを文字列に変換

to_s

10.to_s  => "10"
nil.to_s => ""
true.to_s => "true"

文字列をシンボルに変換

to_sym

string = "apple"
string.to_sym  => :apple

参考文献
=>プロを目指す人のためのRuby入門

7
3
0

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
3