<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>ruby - shungo blog</title>
	<atom:link href="https://shungoblog.com/tag/ruby/feed" rel="self" type="application/rss+xml" />
	<link>https://shungoblog.com</link>
	<description>しゅんごブログ</description>
	<lastBuildDate>Fri, 02 May 2025 11:20:26 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1</generator>

<image>
	<url>https://shungoblog.com/wp-content/uploads/2022/04/cropped-IMG_0718-32x32.jpg</url>
	<title>ruby - shungo blog</title>
	<link>https://shungoblog.com</link>
	<width>32</width>
	<height>32</height>
</image> 
<atom:link rel="hub" href="https://pubsubhubbub.appspot.com"/>
<atom:link rel="hub" href="https://pubsubhubbub.superfeedr.com"/>
<atom:link rel="hub" href="https://websubhub.com/hub"/>
<atom:link rel="self" href="https://shungoblog.com/tag/ruby/feed"/>
	<item>
		<title>【Rails】文字列をBooleanに変換する方法 (ActiveRecord::Type::Boolean.new.cast)</title>
		<link>https://shungoblog.com/programming/rails-string-to-boolean-cast.html</link>
					<comments>https://shungoblog.com/programming/rails-string-to-boolean-cast.html#respond</comments>
		
		<dc:creator><![CDATA[しゅんご]]></dc:creator>
		<pubDate>Tue, 14 Mar 2023 00:29:45 +0000</pubDate>
				<category><![CDATA[プログラミング]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[エンジニア]]></category>
		<guid isPermaLink="false">https://shungoblog.com/?p=2116</guid>

					<description><![CDATA[<p>目次 はじめにActiveRecord::Type::Boolean.new.castで変換するコードの定義についてよく使用する変換例メソッドで定義して使い回す方法クラスメソッドで定義するStringクラスのメソッドとし [&#8230;]</p>
<p>The post <a href="https://shungoblog.com/programming/rails-string-to-boolean-cast.html">【Rails】文字列をBooleanに変換する方法 (ActiveRecord::Type::Boolean.new.cast)</a> first appeared on <a href="https://shungoblog.com">shungo blog</a>.</p>]]></description>
										<content:encoded><![CDATA[<div id="toc" class="toc tnt-number toc-center tnt-number border-element"><input type="checkbox" class="toc-checkbox" id="toc-checkbox-2" checked><label class="toc-title" for="toc-checkbox-2">目次</label>
    <div class="toc-content">
    <ol class="toc-list open"><li><a href="#toc1" tabindex="0">はじめに</a></li><li><a href="#toc2" tabindex="0">ActiveRecord::Type::Boolean.new.castで変換する</a></li><li><a href="#toc3" tabindex="0">コードの定義について</a></li><li><a href="#toc4" tabindex="0">よく使用する変換例</a></li><li><a href="#toc5" tabindex="0">メソッドで定義して使い回す方法</a><ol><li><a href="#toc6" tabindex="0">クラスメソッドで定義する</a></li><li><a href="#toc7" tabindex="0">Stringクラスのメソッドとして定義する</a></li></ol></li></ol>
    </div>
  </div>

<h2><span id="toc1">はじめに</span></h2>
<p>Rubyではboolean判定するには少し工夫が必要です。</p>
<p>自作でメソッドを定義することも可能ですが、<strong>ActiveRecord</strong>に便利なメソッドがあるので、</p>
<p>それを用いてBooleanに変換する方法をご紹介します。</p>
<p>&nbsp;</p>
<h2><span id="toc2"><span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Type</span><span class="o">::</span><span class="no">Boolean</span><span class="p">.</span><span class="nf">new</span><span class="p">.</span><span class="nf">castで変換する</span></span></h2>
<p>下記のようにActiveRecordのメソッドを使用することで</p>
<p>文字列をBooleanに変換することができます。</p>
<div class="hcb_wrap">
<pre class="prism line-numbers lang-ruby" data-lang="Ruby"><code>ActiveRecord::Type::Boolean.new.cast('true') # =&gt; true
ActiveRecord::Type::Boolean.new.cast('false') # =&gt; false
</code></pre>
</div>
<p>&nbsp;</p>
<h2><span id="toc3">コードの定義について</span></h2>
<p>変換するメソッドは下記で定義されています。</p>
<p><a rel="nofollow noopener external" target="_blank" href="https://github.com/rails/rails/blob/61fb58f6a7f852d765d616d1da41d17851ec7afc/activemodel/lib/active_model/type/boolean.rb"><span>rails/activemodel/lib/active_model/type/boolean.rb</span></a></p>
<div class="hcb_wrap">
<pre class="prism line-numbers lang-ruby" data-lang="Ruby"><code>module ActiveModel
  module Type

    ...
    class Boolean &lt; Value
      FALSE_VALUES = [
        false, 0,
        "0", :"0",
        "f", :f,
        "F", :F,
        "false", :false,
        "FALSE", :FALSE,
        "off", :off,
        "OFF", :OFF,
      ].to_set.freeze

      ...
      private
        def cast_value(value)
          if value == ""
            nil
          else
            !FALSE_VALUES.include?(value)
          end
        end
    end
  end
end</code></pre>
</div>
<p>大まかな処理の流れは下記の通りです。</p>
<ol>
<li>valueが空文字&#8221;&#8221; =&gt; nil</li>
<li>valueが<code>FALSE_VALUES</code>に含まれる値 =&gt; false</li>
<li>上記でない =&gt; true<code></code></li>
</ol>
<p>&nbsp;</p>
<h2><span id="toc4">よく使用する変換例</span></h2>
<p><strong>&#8216;true&#8217;</strong>や<strong>&#8216;false&#8217;</strong>以外にもよく使用するであろう値の変換結果を載せておきます。</p>
<div class="hcb_wrap">
<pre class="prism line-numbers lang-ruby" data-lang="Ruby"><code>ActiveRecord::Type::Boolean.new.cast('0') # =&gt; false
ActiveRecord::Type::Boolean.new.cast(0) # =&gt; false
ActiveRecord::Type::Boolean.new.cast('false') # =&gt; false
ActiveRecord::Type::Boolean.new.cast("FALSE") # =&gt; false
ActiveRecord::Type::Boolean.new.cast("off") # =&gt; false
ActiveRecord::Type::Boolean.new.cast("OFF") # =&gt; false

ActiveRecord::Type::Boolean.new.cast('1') # =&gt; true
ActiveRecord::Type::Boolean.new.cast(1) # =&gt; true
ActiveRecord::Type::Boolean.new.cast('true') # =&gt; true
ActiveRecord::Type::Boolean.new.cast('TRUE') # =&gt; true
ActiveRecord::Type::Boolean.new.cast('on') # =&gt; true
ActiveRecord::Type::Boolean.new.cast('ON') # =&gt; true

ActiveRecord::Type::Boolean.new.cast('') # =&gt; nil
ActiveRecord::Type::Boolean.new.cast(nil) # =&gt; nil
</code></pre>
</div>
<p>&nbsp;</p>
<h2><span id="toc5">メソッドで定義して使い回す方法</span></h2>
<p>下記のようにクラスメソッドで定義すれば、かなり使いやすくなるのでオススメです！！</p>
<h3><span id="toc6">クラスメソッドで定義する</span></h3>
<div class="hcb_wrap">
<pre class="prism line-numbers lang-ruby" data-lang="Ruby"><code>class Utility
  def self.to_bool(value)
    ActiveRecord::Type::Boolean.new.cast(value)
  end
end

&gt; Utility.to_bool('true')
true</code></pre>
</div>
<h3><span id="toc7">Stringクラスのメソッドとして定義する</span></h3>
<p>下記にようにStringクラスで定義すれば、文字列全体に適用可能です。</p>
<div class="hcb_wrap">
<pre class="prism line-numbers lang-ruby" data-lang="Ruby"><code>class String
  def to_bool
    ActiveRecord::Type::Boolean.new.cast(self)
  end
end

&gt; 'true'.to_bool
true</code></pre>
</div><p>The post <a href="https://shungoblog.com/programming/rails-string-to-boolean-cast.html">【Rails】文字列をBooleanに変換する方法 (ActiveRecord::Type::Boolean.new.cast)</a> first appeared on <a href="https://shungoblog.com">shungo blog</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://shungoblog.com/programming/rails-string-to-boolean-cast.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>【Ruby】 クラスメソッドからプライベートメソッドを呼ぶ方法</title>
		<link>https://shungoblog.com/programming/ruby-class-and-private-method.html</link>
					<comments>https://shungoblog.com/programming/ruby-class-and-private-method.html#respond</comments>
		
		<dc:creator><![CDATA[しゅんご]]></dc:creator>
		<pubDate>Sun, 12 Mar 2023 12:59:01 +0000</pubDate>
				<category><![CDATA[プログラミング]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[エンジニア]]></category>
		<guid isPermaLink="false">https://shungoblog.com/?p=2105</guid>

					<description><![CDATA[<p>目次 はじめにNGなパターン1. クラスメソッドからプライベートメソッドを呼ぶ2. private内でself.methodを定義するクラスメソッドからプライベートメソッドを呼ぶ書き方 はじめに Rubyでクラスメソッド [&#8230;]</p>
<p>The post <a href="https://shungoblog.com/programming/ruby-class-and-private-method.html">【Ruby】 クラスメソッドからプライベートメソッドを呼ぶ方法</a> first appeared on <a href="https://shungoblog.com">shungo blog</a>.</p>]]></description>
										<content:encoded><![CDATA[<div id="toc" class="toc tnt-number toc-center tnt-number border-element"><input type="checkbox" class="toc-checkbox" id="toc-checkbox-4" checked><label class="toc-title" for="toc-checkbox-4">目次</label>
    <div class="toc-content">
    <ol class="toc-list open"><li><a href="#toc1" tabindex="0">はじめに</a></li><li><a href="#toc2" tabindex="0">NGなパターン</a><ol><li><a href="#toc3" tabindex="0">1. クラスメソッドからプライベートメソッドを呼ぶ</a></li><li><a href="#toc4" tabindex="0">2. private内でself.methodを定義する</a></li></ol></li><li><a href="#toc5" tabindex="0">クラスメソッドからプライベートメソッドを呼ぶ書き方</a></li></ol>
    </div>
  </div>

<h2><span id="toc1">はじめに</span></h2>
<p>Rubyでクラスメソッド内からprivateメソッドを呼び出したときに、</p>
<p>エラーが発生したのでそのときの対処法をご紹介します。</p>
<p>&nbsp;</p>
<h2><span id="toc2">NGなパターン</span></h2>
<h3><span id="toc3">1. クラスメソッドからプライベートメソッドを呼ぶ</span></h3>
<p>私が最初に書いたエラーになるパターンのコードです。</p>
<div class="hcb_wrap">
<pre class="prism line-numbers lang-ruby" data-lang="Ruby"><code>class Sample1
  def self.foo
    bar
  end

  private

    def bar
      puts 'bar'
    end
end

&gt; Sample1.foo
Traceback (most recent call last):
1: from test.rb:13:in `&lt;main&gt;'
test.rb:3:in `foo': undefined local variable or method `bar' for Sample1:Class (NameError)</code></pre>
</div>
<p>&nbsp;</p>
<h3><span id="toc4">2. private内でself.methodを定義する</span></h3>
<p>こちらの場合は、エラーなく実行できますが、</p>
<p>privateメソッドを直接呼び出せてしまっているのでNGですね。</p>
<div class="hcb_wrap">
<pre class="prism line-numbers lang-ruby" data-lang="Ruby"><code>class Sample1
  def self.foo
    bar
  end

  private

    def self.bar
      puts 'bar'
    end
end

// エラーなく実行できる
&gt; Sample1.foo
bar

// privateメソッドを呼べている
&gt; Sample1.bar
bar</code></pre>
</div>
<p>&nbsp;</p>
<h2><span id="toc5">クラスメソッドからプライベートメソッドを呼ぶ書き方</span></h2>
<p>特異クラス内でprivateを定義すれば、</p>
<p>クラスメソッドからプライベートメソッドを呼ぶことが可能になります。</p>
<div class="hcb_wrap">
<pre class="prism line-numbers lang-ruby" data-lang="Ruby"><code>class Sample2
  class &lt;&lt; self # クラスメソッドで定義
    def foo
      bar
    end

    private

      def bar # クラスメソッド内でprivateメソッドを定義する
        puts 'bar'
      end
  end
end

&gt; Sample2.foo
bar</code></pre>
</div>
<p>最初のように<code>def sefl.method end</code>の書き方に合わせるなら</p>
<p>下記のようになります。</p>
<div class="hcb_wrap">
<pre class="prism line-numbers lang-ruby" data-lang="Ruby"><code>class Sample2
  def self.foo # クラスメソッドで定義
    bar
  end
  class &lt;&lt; self

    private

      def bar # 特異クラス内でprivateメソッドを定義する
        puts 'bar'
      end
  end
end

&gt; Sample2.foo
bar</code></pre>
</div><p>The post <a href="https://shungoblog.com/programming/ruby-class-and-private-method.html">【Ruby】 クラスメソッドからプライベートメソッドを呼ぶ方法</a> first appeared on <a href="https://shungoblog.com">shungo blog</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://shungoblog.com/programming/ruby-class-and-private-method.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>【Ruby】ハッシュのキーのシンボル化・文字列化する方法</title>
		<link>https://shungoblog.com/programming/ruby-hash-key.html</link>
					<comments>https://shungoblog.com/programming/ruby-hash-key.html#respond</comments>
		
		<dc:creator><![CDATA[しゅんご]]></dc:creator>
		<pubDate>Fri, 24 Jun 2022 13:17:41 +0000</pubDate>
				<category><![CDATA[プログラミング]]></category>
		<category><![CDATA[ruby]]></category>
		<guid isPermaLink="false">https://shungoblog.com/?p=251</guid>

					<description><![CDATA[<p>目次 ハッシュのキーを変換する方法キーのシンボル化キーの文字列化 ハッシュのキーを変換する方法 キーのシンボル化 使用するメソッド hash.transform_keys(&#38;:to_sym) 使用例 # キーが文 [&#8230;]</p>
<p>The post <a href="https://shungoblog.com/programming/ruby-hash-key.html">【Ruby】ハッシュのキーのシンボル化・文字列化する方法</a> first appeared on <a href="https://shungoblog.com">shungo blog</a>.</p>]]></description>
										<content:encoded><![CDATA[<div id="toc" class="toc tnt-number toc-center tnt-number border-element"><input type="checkbox" class="toc-checkbox" id="toc-checkbox-6" checked><label class="toc-title" for="toc-checkbox-6">目次</label>
    <div class="toc-content">
    <ol class="toc-list open"><li><a href="#toc1" tabindex="0">ハッシュのキーを変換する方法</a><ol><li><a href="#toc2" tabindex="0">キーのシンボル化</a></li><li><a href="#toc3" tabindex="0">キーの文字列化</a></li></ol></li></ol>
    </div>
  </div>

<h2><span id="toc1">ハッシュのキーを変換する方法</span></h2>
<h3><span id="toc2">キーのシンボル化</span></h3>
<p>使用するメソッド</p>
<pre><span class="nb">hash</span><span class="p">.</span><span class="nf">transform_keys</span><span class="p">(</span><span class="o">&amp;</span><span class="ss">:to_sym</span><span class="p">)
</span></pre>
<p>使用例</p>
<pre># キーが文字列のハッシュを定義
&gt; hash_string = {"key1" =&gt; "value1", "key2" =&gt; "value2", "key3" =&gt; "value3"}
=&gt; {"key1" =&gt; "value1", "key2" =&gt; "value2", "key3" =&gt; "value3"}

# キーのシンボル化
&gt; hash_string.transhform_keys(&amp;:to_sym)
=&gt; {:key1 =&gt; "value1", :key =&gt; "value2", :key3 =&gt; "value3"}
</pre>
<h3><span id="toc3">キーの文字列化</span></h3>
<p>使用するメソッド</p>
<pre><span class="nb">hash</span><span class="p">.</span><span class="nf">transform_keys</span><span class="p">(</span><span class="o">&amp;</span><span class="ss">:to_s</span><span class="p">)
</span></pre>
<p>使用例</p>
<pre># キーがシンボルのハッシュを定義
&gt; hash_key = {:key1 =&gt; "value1", :key =&gt; "value2", :key3 =&gt; "value3"}
=&gt; {:key1 =&gt; "value1", :key =&gt; "value2", :key3 =&gt; "value3"}

# キーの文字列化
&gt; hash_key.transhform_keys(&amp;:to_s)
=&gt; {"key1" =&gt; "value1", "key2" =&gt; "value2", "key3" =&gt; "value3"}</pre><p>The post <a href="https://shungoblog.com/programming/ruby-hash-key.html">【Ruby】ハッシュのキーのシンボル化・文字列化する方法</a> first appeared on <a href="https://shungoblog.com">shungo blog</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://shungoblog.com/programming/ruby-hash-key.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
