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.

Ruby配列系のメソッド(その他編)

Posted at

LeetCodeでアルゴリズム学習をするあたり、使った配列系のメソッド、便利な書き方を紹介いたします。
新しいものを使ったら随時更新していこうと思います。

【配列の要素を2倍にする】

● *

nums = [1,2,1]
def method(nums)
	nums * 2
end

p nums
=> [1,2,1,1,2,1]

【配列の要素の数を返す】

● length

nums = [1,2,1]
p nums.length
=> 3

##  lengthは文字列の文字数もカウントできる

【配列を定義せずにそのまま配列を返す書き方】

● [1, 2, 3]

def array()
  return [1, 2, 3]  
end

## 上記の書き方によって【array =  []】のような定義を省ける

【配列に含むか判定・カウント】

● include?

##  配列に特定の要素が含まれている判定
nums = [1, 2, 3, 4]
nums.include?(4)
=> true

● count

## 配列に特定の要素が何個含まれているか判定
nums = [1, 2, 1, 4]
nums.count(1)
=> 2

【配列の要素を結合する】

● join

## 配列の要素を結合し、配列から取り出す
array = ["スプーン", "フォーク"]
array.join(",")
=> スプーン, フォーク
0
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
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?