LoginSignup
12
10

More than 5 years have passed since last update.

RubyとJavaScriptの書き方を比較する

Posted at

元々JavaScriptプログラマーだったのですが、今年からRubyでプログラミングすることになりました。凡そ2ヶ月経ってましたので、Rubyの書き方はJavaScript(ES6以降)とよく似てるところや微妙な違いがあるところなどを纏めようかなと思います。

変数

ruby
color = "red"
javascript
let color = "red"

定数

rubyは定数を示す予約語すら不要ですので、アルファベット大文字 ([A-Z]) で始まる識別子は定数と認識します。

ruby
FOO = 'FOO'
javascript
const FOO = 'FOO'

文字列の式展開

ruby
foo = "abc"
p "hello, #{foo}" #=> "hello, abc"
javascript
foo = "abc"
console.log(`hello, ${foo}`); // hello, abc

メソッド

rubyがOOPなのでメソッドと言いますが、JavaScriptで関数(function)と呼ばれます。

ruby
def say(sentence)
  puts sentence
end
javascript
function say(sentence) {
  console.log(sentence);
}

const say2 = (sentence) => {
  console.log(sentence)
}

分割代入

rubyが変数の分割代入できますが、Hashや配列ができません。

ruby
a, b = 1, 2
# a:1
# b:2

a, b, *c = 1, 2, 3, 4, 5
# a:1
# b:2
# c:[3, 4, 5]
javascript
[a, b] = [1, 2]
// a:1
// b:2

[a, b, ...c] = [1, 2, 3, 4, 5]
// a:1
// b:2
// c:[3, 4, 5]

{c, d} = {c:3, d:4}
// c:3
// d:4

{a, b, ...c} = {a:1, b:2, c:3, d:4, e:5]
// a:1
// b:2
// c:{c:3, d:4, e:5}

参考記事

12
10
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
12
10