LoginSignup
7
7

More than 5 years have passed since last update.

Ruby | 文字列リテラル同士の標準的な結合方法と標準的ではない結合方法

Last updated at Posted at 2014-08-31

Ruby | 文字列リテラル同士の標準的な結合方法と標準的ではない結合方法

概要

文字列リテラル同士の標準的な結合方法と標準的ではない結合方法について。
きっかけは、Twitterで

"a" "b"

が文字列結合になる、というつぶやきを見たことです。
1年以上Rubyを使っていますが全く知りませんでした。

サンプルコード

# 標準的な文字列結合
text = "a" + "b"
puts text

# String#<<、による文字列結合
text = "a"<<"b"
puts text

# String#<<、による文字列結合(ASCII Code)
text = "a"<<98
puts text

# String#concat、による文字列結合
text = "a".concat("b")
puts text

# String#concat、による文字列結合(ASCII Code)
text = "a".concat(98)
puts text

# -----------------------------------------------
# ここからは普段あまり利用する機会のない連結方法
# -----------------------------------------------

# スペース区切りによる文字列結合(タブでも可)
text = "a" "b"
puts text

# スペース区切りによる文字列結合(シングルクォートダブルクォート混在)
text = "a" 'b'
puts text

# 区切りなし、による文字列結合
text = "a""b"
puts text

# 区切りなし、による文字列結合(シングルクォートダブルクォート混在)
text = "a"'b'
puts text

※そもそも想定されていない文法になっているためか、シンタックスハイライトがうまく動作しないので、
無効にしました。

出力

ab
ab
ab
ab
ab
ab
ab
ab
ab

関連記事

Nabetani さんの 「ruby の 文字列の連接」
http://qiita.com/Nabetani/items/29a82811e95f80edbb27

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