@daigo01090118 (daigo ikeda)

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

rails のto_sについて

to_sメソッドについて教えてください

Ruby on Railsでサンプルアプリを作っているのですが、

application_helper.rbの中に記載する
moduleの中で、

条件分岐をさせているようなコードがあるのですが、どんな動作をしているのかわかりません

1.   module ApplicationHelper
2.   def bs4_bgcolor_for(flash_key)
3.      case flash_key
4.      when "success"
5.       "alert-success"
6.      when "error"
7.        "alert-danger"
8.      when "alert"
9.       "alert-warning"
10.      when "notice"
11.        "alert-info"
12.      else
13.        flash_key.to_s
14.      end
15.    end
16.  end

上のコードの13行目

[flash_key]という引数に対して

与えられている[.to_s]はなんのために与えているのでしょうか

これがなんのためにあるのかが分からなくて気になります

有識者の方解説お願いします。

0 likes

1Answer

Rails のメソッドの意味を知りたいときはまず「Ruby to_s」か「Rails to_s」で検索してみてください。普通なら公式のリファレンスマニュアルをおすすめしたいところですが、 Rails はマニュアルだけ読んでも分かりづらいので解説記事を探した方がいいです。

さて、 to_s は値の文字列表現を返すメソッドです: https://docs.ruby-lang.org/ja/latest/method/Object/i/to_s.html

ほぼすべてのクラスの祖先である Objectクラスが to_s メソッドを実装しているので、ほとんどどんな値に対しても to_s を呼び出すことができます:

:a_symbol.to_s == 'a_symbol'
'a_string'.to_s == 'a_string'
42.to_s == '42'

class Klass; end
Klass.to_s == 'Klass'

ご質問のコードでは、 flash_key が条件のどの値とも一致しなかったときに flash_key.to_s でそれ自体を文字列化して返しています。

0Like

Comments

  1. @daigo01090118

    Questioner

    分かりやすい解説ありがとうございました!
    おかげで理解が進みました!

Your answer might help someone💌