Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | 配列 | 部分配列の取得

パンくず

Ruby
配列
部分配列の取得

概要

Rubyの配列の一部を取得剃る方法について

構文

array[a,b] # => arrayのa-1番目からb-1番個分を部分配列として取得
array[a..b] # => arrayのa-1番目からb-1番目までを部分配列として取得
array[a...b] # => arrayのa-1番目からb-2番目までを部分配列として取得

サンプル

# -*- encoding: utf-8 -*-
require "pp"

numbers = %w[one two three four five]
pp numbers[2,3]
pp numbers[2..3]
pp numbers[2...3]

出力

["three", "four", "five"]
["three", "four"]
["three"]