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 3 years have passed since last update.

Rubyの便利だと思ったメソッド

Last updated at Posted at 2020-09-14

やっていて便利だと思ったメソッドをメモ書き。
※ 本当にただのメモです。

文字列の出現回数を数える

一文字

str = "aaabbbcccabc"  str.count("a") => 4

複数文字

str = "aaabbbcccabc"  str.scan("ab") => [ab, ab]  str.scan("ab").length => 2

## 絶対値を取得
num = 5  num.abs => 5
num = (-5)  num.abs => 5

## 文字列の一部を置き換え
str = "aabbcc"  str.gsub("aa", "") => str = bbcc

aaを空文字に置き換え

文字列の一部を削除

末尾から削除

str = "aabbcc"  str.chomp("cc") => aabb

どこでも削除

str = "aabbcc"  str.delete("bb") => aacc

大文字 ⇄ 小文字

str = "abc"  str.upcase => ABC  str.downcase => abc

## 配列

生成

(1..5).to_a => [1, 2, 3, 4, 5]

追加

末尾

array = ["a", "b", "c"]  array.push("e"); array = ["a", "b", "c", "e"]

先頭

array = ["a", "b", "c"]  array.unshif("e"); array = ["e", "a", "b", "c"]

削除

array = ["a", "b", "c", "e"]  array.delete("e") array = ["a", "b", "c"]  array[0,2] = [] array = ["c"]

添字0から2つ削除

置き換え

array = ["a", "b", "c"]  array.map!{|x| x=="a" ? "z" : x} => ["z", "b", "c"]

二つの配列の結合

arrayX = [1, 2, 3]  arrayY = ["a", "b", "c"]  arrayX.concat(arrayY) arrayX = [1, 2, 3, "a", "b", "c"]

重複を削除

array = [1, 1, 2, 2, 3, 3]  array.uniq => [1, 2, 3]

反転

array = ["a", "b", "c"]  array.reverse! => ["c", "b", "a"]

文字列を一文字ずつ分割

str = "abc"  str.chars => ["a", "b", "c"]
num = 12345  num.chars => [1, 2, 3, 4, 5]

結合した文字列の作成

array = ["a", "b", "c"]  array.join => "abc"

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?