1
0

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 1 year has passed since last update.

RubyでPythonのようにfor i in range(n)する

Posted at

普通のコード

rubyの普通のrangeオブジェクトだとこうです

(0...n).each do |i|
  puts i
end

for文で書き直すと以下。

for i in 0...n
  puts i
end

range関数

しかし、私はPythonのようにrangeを書きたいと思いました。
そこで、以下の関数を定義します。

def range(l, r=nil, s=nil)
  return 0...l unless r
  return l...r unless s
  (l...r).step(s)
end

range(l)のとき、0...lを返す。
range(l, r)のとき、l...rを返す。
range(l, r, s)のとき、(l...r).step(s)を返す。

使い方は以下です。※コロンは不必要、endは必要です。

for i in range(10, 20, 2)
  puts i
end
#=> 10
#=> 12
#=> 14
#=> 16
#=> 18
1
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?