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 1 year has passed since last update.

【Ruby】Rubyのわかりにくい文法

Last updated at Posted at 2022-09-17

ハッシュの記法の色々

Railsコンソール
# ハッシュのキーを文字列で
>> user = { "name" => "tarou", "email" => "tarou@example.com" }
=> {"name"=>"tarou", "email"=>"tarou@example.com"}

# ハッシュのキーをシンボルで
>> user = { :name => "test", :email => "test@example.com" }
=> {:name=>"test", :email=>"test@example.com"}

>> user[:name]              # :nameキーにアクセス
=> "test"

>> user[:test]          # 存在しないキーに対応する値にアクセスするとnil
=> nil

そして、Rubyでおそらく一番よく目にする、
この記法に至る

>> user = { name: "test", email: "test@example.com" }
=> {:name=>"test", :email=>"test@example.com"}

ハッシュがメソッド呼び出しの最後の引数である場合は、波カッコを省略できる。

# Railsで見かける例のやつ
stylesheet_link_tag 'application', { media: 'all',
                                     'data-turbolinks-track': 'reload' }
# 上は以下のように書いても同じ
stylesheet_link_tag 'application', media: 'all',
                                   'data-turbolinks-track': 'reload'


user = User.new({name: "test", email: "test@example.com"})

user = User.new(name: "test", email: "test@example.com")

mapの省略記法

>> %w[A B C].map { |f| f.downcase }
=> ["a", "b", "c"]
>> %w[A B C].map(&:downcase)
=> ["a", "b", "c"]
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?