def arithmetic_sequence(init: 1, diff: 1, count: 10)
current = init
if block_given?
count.times do
yield(current)
current += diff
end
else
# tapメソッドのブロックではArray.newに対して設定する
Array.new.tap do |a|
count.times do
a << current
current += diff
end
end
end
end
# blockが渡された場合
arithmetic_sequence(init: 2, diff: 3, count: 5) do |n|
puts n
end
=begin
結果 => 2
5
8
11
14
=end
# block渡されていない場合
p arithmetic_sequence(init: 2, diff: 3, count: 5)
# 結果 => [2, 5, 8, 11, 14]
More than 5 years have passed since last update.
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme
List of users who liked
11