LoginSignup
1
1

More than 1 year has passed since last update.

[Ruby]Stringクラスのsliceメソッド

Last updated at Posted at 2022-01-10

学習したことのアウトプットとして

sliceメソッド

rubyの組み込みライブラリ
配列や文字列から指定した要素を取り出すことができるメソッド
取り出したとしても、配列や文字列はもとのまま
例)

# 配列を作成します
array = [0,1,2,3,4,5,6]

# 配列から引数で指定した要素を取得します
ele1 = array.slice(1)
puts ele1
#=> 1

# 配列番号-4から4つ分の要素をsliceします
ele2 = array.slice(-4,4)
puts ele2
#=> 3, 4, 5, 6

# 配列はもとのままです
puts array 
#=> [0,1,2,3,4,5,6]

slice!(破壊的メソッド)だとオブジェクト自身の内容は変更される
例)

string = "this is a string"
string.slice!(2)        #=> "i"
string.slice!(3..6)     #=> " is "
string.slice!(/s.*t/)   #=> "sa st"
string.slice!("r")      #=> "r"
puts string             #=> "thing"

※補足等ありましたらコメントいただけると幸いです

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