1
1

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 5 years have passed since last update.

puts, print, pの違いと、値出力時の便利メソッドまとめ

1
Last updated at Posted at 2019-04-14

初めに

paizaでやっていて値の出力方法がよく分からなくなってきたので、自分なりにメモしておきます。

puts, print, pの違い

putsメソッド

引数のオブジェクトを標準出力。

末尾に改行が入る形で出力される
・to_sメソッドで文字列に変換

printメソッド

引数のオブジェクトを標準出力。

・改行されない
・to_sメソッドで文字列に変換

pメソッド

引数のオブジェクトを詳しく標準出力。

・改行される
・出力する値と共に型情報を一緒に出力
 (文字列→””で囲んで出力、数値→そのまま出力)

結論

特徴だけまとめると、
・printは、改行を行わないputs
・pは、文字列なら "" 囲むputs
です。

出力例

apple = "りんご"
orange = "みかん"
 
print apple
puts orange
p orange


# => appleorange
# => "orange"
apple = "りんご"
orange = "みかん"
 
print apple, orange
puts apple, orange
p apple, orange


# => appleorangeapple
# => orange
# => "apple"
# => "orange"
p 1
p "1"
puts 1
puts "1"


# => 1
# => "1"
# => 1
# => 1

出力時の便利メソッド

times

・同じパターンを繰り返したい

4.times do |i|
puts "りんごが#{i+1}個あります"
end


# => りんごが1個あります
# => りんごが2個あります
# => りんごが3個あります
# => りんごが4個あります

join

・配列同士をくっつけたい
・出力結果の間に空欄を空けたい

array = ["りんご", "みかん", "バナナ"]

puts array.join(" + ")
puts array.join(" - ")
puts array.join(" ")


# => りんご + みかん + バナナ
# => りんご - みかん - バナナ
# => りんご みかん バナナ
1
1
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?