LoginSignup
1
1

More than 5 years have passed since last update.

Ruby block_given?

Last updated at Posted at 2015-02-09

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]

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