はじめに
この記事は普段プログラム書いてて「あれ?○○だとこう書くんだけど、この言語はどう書くんだっけ?」ということがよくあるので主に自分向けの備忘録として書いたものです。内容は都度追加していく予定です。
現在、主に使っているのがRuby、Python、JavaScriptなのでそれらの比較が多いです。
制御構造
else if
Ruby - elsif
if a > 0
puts 'plus'
elsif a < 0
puts 'minus'
end
Python - elif
if a > 0:
print('plus')
elif a < 0:
print('minus')
JavaScript - else if
if (a > 0) {
console.log('plus');
} else if (a < 0) {
console.log('minus');
}
switch的構文
Ruby - case when
case a
when 1
puts 'one'
when 2
puts 'two'
end
Python
そんなものはない(関羽略)
JavaScrpt - switch case
break忘れないように。
switch (a) {
case 1:
console.log('one');
break;
case 2:
console.log('two');
break;
}
データ型全般
falseになるもの
Ruby - nil
むしろfalseにならないものの方が多い。
p nil || 1
p [] || 1
p '' || 1
p 0 || 1
Python - None、空配列や空文字列、0
Falseになるものが多いのでしばらくPython書いた後に別言語に行くと注意。
print(None or 1)
print([] or 1)
print('' or 1)
print(0 or 1)
Javascript - undefined、null、空文字列、0
空配列はtrue。forとかで回すと結局回らないことになるけど、ifで条件分岐後、for前後で何かしている場合は注意(arr.len != 0
と条件を書こう)
console.log(undefined || 1);
console.log(null || 1);
console.log([] || 1); // 空配列はtrue
console.log('' || 1);
console.log(0 || 1);
join
言語により配列(的)クラスにjoinがあるか文字列クラスにjoinがあるかが異なる。
Ruby - Array#join
[1, 2, 3].join(',')
Python - str.join
罠のうえに連結要素は文字列じゃないといけない。
a = [1, 2, 3]
','.join([str(e) for e in a])
JavaScript - Array#join
[1, 2, 3].join(',')
配列
Pythonは配列ではなくリストであり、配列は別にあるのだがここでは「配列」という言葉でまとめる。
要素を繰り返し処理
Ruby - Array#each
arr = [1, 2, 3]
arr.each {|e| p e}
Python - for in
arr = [1, 2, 3]
for e in arr:
print(e)
JavaScript - for ofかArray#forEach
for ofの方が関数呼び出しじゃないので好きだけど、for inと間違えやすいからArray#forEachの方がいいのかも。
※対話環境に貼り付け実行しやすいようにvarもletもconstも付けてませんが、もちろんファイルに書くときは適切なものを付けてください。
arr = [1, 2, 3];
for (let e of arr) {
console.log(e);
}
arr.forEach(e => console.log(e));
条件を満たすものを取り出す
Ruby - Array#select
arr = [1, 2, 3, 4, 5]
p arr.select{|e| e % 2 == 0}
Python - filter
第1引数が条件チェックの関数。
また、filter関数の戻り値はイテレータを実装したfilterオブジェクトなので配列が欲しかったらlist関数に渡す必要あり(ていうかfilterもlistも正確にはコンストラクタ。mapなどの他の関数も同様)
arr = [1, 2, 3, 4, 5]
print(list(filter(lambda e: e % 2 == 0, arr)))
↓@shiracamusさんの編集リクエストより。内包表記のような「書き方が大きく異なる(それを忘れることはない)」記述方法は本筋ではないですが、せっかくなので採用させていただきます。
または
arr = [1, 2, 3, 4, 5]
print([e for e in arr if e % 2 == 0])
JavaScript - Array#filter
arr = [1, 2, 3, 4, 5];
console.log(arr.filter(e => e % 2 == 0));
文字列
部分文字列
Ruby - []でRangeを指定
しばらく触ってないとsubstr的メソッドを探してしまう(笑)
s = 'abcdefg'
p s[3..-1]
Python - []でスライスを指定
Rubyみたいにs[3:-1]
だと末尾が含まれなくなるの注意。
s = 'abcdefg'
print(s[3:])
JavaScript - String#substr
substringメソッドもある。
s = 'abcdefg';
console.log(s.substr(3));
いつの間にかsubstrは非推奨メソッドになってた。長さで指定できた方が便利なのに、と思ったけどRubyやPythonも末尾指定するときはindexか。