LoginSignup
2
1

More than 5 years have passed since last update.

メソッド内での定数への文字列追加に<<が使用可能

Last updated at Posted at 2015-01-17

Q.エラーが出る選択肢を以下から選択。

問題
X = "abc"
class Foo
  def bar
    # ここに選択肢を入れる
  end
end
p Foo.new.bar
選択肢
 (1) X
 (2) X =  "def"
 (3) X += "def"
 (4) X << "def"
解答
(2),(3)

メソッドの中で定数の定義を行うことはできないので、
(2)と(3)はエラーが出る。

(4)がWaningなども出ず実行できることが意外!

補足で後述するが <<String#concatの別名。
定数に対しても<<が使用できるとは知らなかった。
調べても情報が見つからない。

X = "abc"

class Foo
  def bar
    X
  end
end

p Foo.new.bar
出力
"abc"

X = "abc"

class Foo
  def bar
    X =  "def"
  end
end

p Foo.new.bar
出力
constant.rb:5: dynamic constant assignment
    X =  "def"
       ^

X = "abc"

class Foo
  def bar
    X += "def"
  end
end

p Foo.new.bar
出力
constant.rb:5: dynamic constant assignment
    X += "def"
        ^

X = "abc"

class Foo
  def bar
    X << "def"
  end
end

p Foo.new.bar
出力
"abcdef"

補足

class String

ただし、この命名ルールを 「破壊的なメソッドにはすべて『!』が付いている」と解釈しないでください。 例えば concat には「!」が付いていませんが、破壊的です。あくまでも、 「『!』が付いているメソッドと付いていないメソッドの両方があるときは、 『!』が付いているほうが破壊的」というだけです。 「『!』が付いているならば破壊的」は常に成立しますが、逆は必ずしも成立しません。

instance method String#<<

self << other -> self
concat(other) -> self

self に文字列 other を破壊的に連結します。 other が 0 から 255 のまでの整数である場合は その 1 バイトを末尾に追加します (つまり、整数が示す ASCII コードの文字が追加されます)。

self を返します。
[PARAM] other:
文字列もしくは 0 から 255 までの範囲の整数

str = "string"
str.concat "XXX"
p str    # => "stringXXX"

str << "YYY"
p str    # => "stringXXXYYY"

str << 65  # 文字AのASCIIコード
p str    # => "stringXXXYYYA"

標準クラス・モジュール > String > <<

(Oiaxリファレンス)
<< (String)

other_str

str << other_str

<<演算子(メソッド)は、文字列strの末尾に別の文字列other_strを加えます。+とは違い、レシーバ自身の文字列を変更します。戻り値はレシーバ自身です。

concatメソッドは<<の別名です。

s = "Hello"
s << ", world"
puts s
#=> Hello, world

integer

str << integer

文字列の代わりに整数で文字のコードを指定すると、文字列の末尾に1文字追加します。指定できる整数は0から255です。

s = "Hello, world"
s << 0x21
puts s
#=> Hello, world!

Ruby 1.9 Ruby 1.9では256以上の整数を指定できます。Shift_JISの文字列に2バイトの文字を追加したり、UTF-8の文字列にユニコード番号で文字を追加したりできます。

参考にしたツイート

以下のツイートにインスパイアされて記事を書きました。
参考: 武田哲也さんのRuby技術者認定試験受験記

2
1
4

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
2
1