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

Python to RubyAdvent Calendar 2021

Day 14

[py2rb] sliceクラス

Last updated at Posted at 2021-12-14

はじめに

移植やってます。

slice (Python)

s = slice(0, 10, 3)
print(type(s))

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10][s]
# a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10][s.start:s.stop:s.step]
print(a)

# <class 'slice'>
# [1, 4, 7, 10]

Pythonってsliceクラスがあるんですね。
3つの数値を持ったタプルなんだと思いますが。

どうする? (Ruby)

slice = Struct.new(:start, :stop, :step)
s = slice.new(0, 5, 3)
puts s
puts s.class
puts s.instance_of?(slice)

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10][s.start, s.stop]
print(a)

# #<struct start=0, stop=5, step=3>
# #<Class:0x000001e08c9f3260>
# true
# [1, 2, 3, 4, 5]

Structで代用できそうな気もします。
Sliceクラスを作る?

class Slice
  attr_reader :start, :stop, :step

  def initialize(start, stop, step)
    @start = start
    @stop = stop
    @step = step
  end

  def slice(array)
    @start = 0 if @start.nil?
    @stop = -1 if @stop.nil?
    if @step.nil?
      array[@start..@stop]
    else
      array[@start..@stop].select.with_index{ |num, i| i % @step == 0 }      
    end
  end
end

s = Slice.new(0, nil, 3)
puts s.class

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(s.slice a)

# Slice
# [1, 4, 7, 10]

メモ

  • Python の sliceクラス を学習した
  • 道のりは遠そう
0
0
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
0
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?