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とzshの配列操作比較表

Last updated at Posted at 2023-06-23

配列操作の比較表: Ruby, Python, JavaScript, Perl, C++ - bkブログ のzsh版です。
zshってここまでできたんだ…

Ruby zsh
a = [1, 2, 3] a=(1 2 3)
a.length $#a
a.empty? $#a = 0
a.push(x)
a << x
a+=$x
a.unshift(x) a=($x $a)
a.pop a=($a[1,-2])
a.shift shift a
a.concat(b) a=($a $b)
a.clear a=()
a.insert(i, x) a=(${a::(($i-1))} $x ${a[$i,$#a]}))
a.delete(x) a=${a:#$x}
a.delete_at(i) a=(${a::(($i-1))} ${a[(($i+1)),$#a]})
a.nitems {|e| e == x } -
a.include?(x) ${a[(Ie)$x]}
(Ie)だとexact match。(I)だとpattern match
a.index(x) ${a[(Ie)$x]}
a.first ${a[1]}
添字は1始まり
a.last ${a[-1]}
a[i,l]
a.slice(i, l)
-
a[i..j]
a.slice(i..j)
${a[$i,$j]}
a[i...j]
a.slice(i...j)
-
a.sort ${(o)a} アルファベット順ソート
${(n)a} 数値順ソート
a.sort! -
a.reverse ${(O)a}
a.reverse! -
a.uniq -
a.uniq! typeset -U a
a.join(d) ${(j:,:)a}
,で連結。区切り文字は任意だが変数は使えない
a.each {|x| ... } for i in $a; do ... ; done
a.is_a?(Array) "$(declare -p a)" =~ "-a"

${(o)a}${(j:,:)a}の記法は man zshexpn の「PARAMETER EXPANSION」->「Parameter Expansion Flags」に記載されている。

おまけ:文字列を配列にsplitする

Ruby zsh
a = s.split(',') a=(${(s:,:)s})
a = s.split(':') a=(${(s/:/)s})
a = s.split("\n") a=${(f)s}
a = s.split("\0") a=${(0)s}
- a=${(z)s}
zshの文法に従って単語に分割する

おまけ2:mapやselect

select: ${(M)配列名:#パターン}
reject: ${配列名:#パターン}
find: ${配列名[(r)条件]}
find_index: ${配列名[(i)条件]}
map: パターンマッチによる置換くらいなら下記でできる

arr5=("aaa,111" "bbb,222" "ccc,333")

echo ${(M)arr5#*,} #=> aaa, bbb, ccc,
echo ${(M)arr5%,*} #=> ,111 ,222 ,333

echo ${(R)arr5#*,} #=> 111 222 333
echo ${(R)arr5%,*} #=> aaa bbb ccc

参考

zsh の配列操作の基本から応用まで - Qiita
zshの連想配列の使い方まとめ - Qiita
zsh の分かりにくい記号、用語のまとめ - Qiita

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?