1
0

More than 1 year has passed since last update.

sliceメソッドを使ったプログラムの備忘録

Posted at

今日も学んだことを忘れないためにメモします。

sliceメソッドとは

配列や文字列から指定した要素を取り出すことができるメソッド。

array = [0,1,2,3,4,5,6]
puts array 
#=> [0,1,2,3,4,5,6]

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

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

文字列だけでなく、配列、ハッシュからも取り出せる(ハッシュの場合はActiveSupportという外部ライブラリーを使う)

# 配列からslice
array = ["Ruby","Python","Java"]
puts array.slice(0)

# 出力結果
#=> Ruby


# ハッシュからslice
require 'active_support'
hash = {"Ruby":"Rails","Python":"Django","PHP":"CakePHP"}
puts hash.slice(:Ruby,:Python)
puts hash.slice(:Ruby,:PHP)

# 出力結果
{:Ruby=>"Rails", :Python=>"Django"}
{:Ruby=>"Rails", :PHP=>"CakePHP"}

プログラム内容

対象の文字列から末尾にある2文字を取得し、取得した2文字を3回繰り返して出力する。

記述内容

def extra_end(str)
  puts  str.slice(-2,2) * 3
 end
 
extra_end('Hello')
extra_end('ab')
extra_end('Hi')

# 出力結果
#=> lololo
#=> ababab
#=> HiHiHi

以上になります。

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