0
0

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 3 years have passed since last update.

シンボルについて学習したこと

Last updated at Posted at 2020-06-03

###シンボルを作成する上での注意点

エラーが出る書き方
#識別子として無効な文字列(数字で始まる、ハイフン、スペースを含む文字列)を使うとエラーが発生
:5678             #=>SyntaxError
:rails-is-easy    #=>Nameerror
:rails is easy    #=>SyntaxError
:()               #=>SyntaxError

#シングルクオートで囲むとシンボルとして有効
:'5678'           #=>"5678"
:'rails-is-easy'  #=>"rails-is-easy"
:'rails is easy'  #=>"rails is easy"
:'()'             #=>"()"
シンボルの中で式展開
#ダブルクオートを使う
title = 'Taro'
:"#{title.upcase}" #=> :TARO

###シンボルと文字列
文字列とシンボルは別物なので、互換性はない。しかし、文字列をシンボルに変換するメソッド、シンボルを文字列にするメソッドはある。

string = 'ruby'
sypbol = :ruby
string == symbol #=> false

#to_symメソッド:文字列をシンボルに変換
string.to_sym           #=> :ruby 
string.to_sym == symbol #=> true

#to_sメソッド:シンボルを文字列に変換
symbol.to_s           #=> "ruby" 
symbol.to_s == string #=> true  

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

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?