##式展開
Ruby
cat = "maru"
p "こんにちは#{cat}ちゃん" #=> "こんにちはmaruちゃん"
「`」(バッククオート)で文字列を囲うことで、文字列で変数を使用
JavaScript
var cat = 'maru';
console.log(`こんにちは${cat}ちゃん`); //=> こんにちはmaruちゃん
##Enumerator#each
Ruby
[1, 2, 3].each do |val|
p val
end #=> 1, 2, 3
JavaScript
//es6
for (let v of [1, 2, 3]) {
console.log(v) //=> 1, 2, 3
}
//es5
[1, 2, 3].forEach(val => {
console.log(val); //=> 1,2,3
});
##アロー記法(Rubyのラムダ式)
Ruby
foo = ->(x) { x * x }
foo[5] #=> 25
JavaScript
var foo = ( x ) => { return x * x };
console.log(foo(5)) // => 25
##デフォルト引数
Ruby
def even(value = 10)
(1..value).each do |val|
if val.even?
p val #=> 2,4,6,8,10
end
end
end
even
JavaScript
function even(count = 10) {
for (var i = 1; i < count; i++) {
if(i % 2 === 0){
console.log(i) //=> 2,4,6,8,10
}
}
}
even();
##可変長引数
Ruby
def cat(*nya)
p nya
end
cat(["punch", "punch", "punch"])
#=> "punch", "punch", "punch"
JavaScript
function cat(...nya) {
console.log(nya);
}
cat('punch', 'punch', 'punch');
//=> [ 'punch', 'punch', 'punch' ]
##ブロックスコープ
Ruby
integer = "cat"
[1, 2, 3, 4, 5].each do |val|
integer = val
p integer #=> 1,2,3,4,5
end
puts integer #=> "cat"
JavaScript
var integer = 'cat';
[1,2,3,4,5].forEach(val => {
let integer = val;
console.log(integer); //=> 1,2,3,4,5
});
console.log(integer); //=> 'cat'
##与えられたオブジェクトを要素とする集合
Ruby
require 'set'
set = Set[1,2,3,5,1]
p set #=> #<Set: {1, 2, 3, 5}>
set.add(3)
set.add(10)
p set #=> #<Set: {1, 2, 3, 5, 10}>
JavaScript
var set = new Set([1,2,3,5,1]);
console.log(set) //=> Set {1, 2, 3, 5}
##Hashオブジェクト
Ruby
my_map = { one: "lion", two: "gorilla", three: "rabbit" }
p my_map #=> { :one => "lion", :two => "gorilla", :three => "rabbit" }
JavaScript
var myMap = new Map();
myMap.set('one', "lion")
myMap.set('two', "gorilla")
myMap.set('three', "rabbit")
console.log(myMap); //=> Map {"one" => "lion", "two" => "gorilla", "three" => "rabbit"}
##定数
Ruby
HOGE = 7
p HOGE #=> 7
JavaScript
const hoge = 7;
var hoge = 11; //=> Duplicate declaration "hoge"
console.log(hoge); //=> 7