前言
之前用javascript做了可以实现 报名-竞价 活动的party bid,如今用ruby语言为party_bid做了个服务端,可以创建用户,每个用户都可以组织自己的party_bid活动,并且设置的管理员可以看到所有用户信息,并对这些用户信息进行管理。
这前后分别学习了js与ruby,对它们有了初步的认识,现在对它们之间的共性与不同做个简单的总结。
正文
1. 大概简介
Ruby:Ruby 是一种面向对象、命令式、函数式、动态的通用编程语言,其设计理念是人性化,程序员可以不用写很多代码就能实现想要的功能,多用于后台服务端。
Javascript:JavaScript 是一种广泛应用于客户端网页(浏览器)开发的脚本语言,可以给 HTML 网页添加动态功能,响应用户的各种操作,被广泛用于客户端。
2. 正式PK
Array: |
Ruby: | a = ["1", "2"]
a.push("3")
a.map!(&:to_i) # [1, 2, 3] |
JS: | var a = ["1", "2"];
a.push("3");
a = a.map(function(n) { return parseInt(n, 10); }); |
遍历方法的使用:
Ruby: | a = [1, 2, 3]
a.each {|n| puts n}
#or
a.each do |n|
puts n
end
#or
for i in 0..(a.length - 1) do
puts a[i]
end |
JS: | var a = [1, 2, 3];
a.forEach(function(n) { console.log(n); })
//or
for (var i = 0; i < a.length; i++) {
console.log(a[i]);
} |
Strings: |
获取字符串的索引:
Ruby: | 'hello'.index('e') # 1
'hello'.rindex('l') # 3 |
JS: | 'hello'.indexOf('e') // 1
'hello'.lastIndexOf('l') // 3 |
判断字符串的值:
Ruby: | if 'hello'.include? 'lo'
puts 'found'
end |
JS: | if (~'hello'.indexOf('lo')) {
console.log('found');
} |
新建字符串:
Ruby: | 'hello' * 3 # 'hellohellohello' |
JS: | (new Array(3 + 1)).join('hello')
// 'hellohellohello' |
Hash: |
定义(方法一样):
Ruby: | h = {}
h['a'] = 1
h['b'] = 2 |
JS: | var h = {};
h['a'] = 1;
h['b'] = 2; //以下两个用例中的h即为此处定义的h |
遍历:
Ruby: | h.each {|key, value| puts "#{key} #{value}" } |
JS: | for (key in h) { console.log(key, h[key]); } |
取属性:
Ruby: | h.keys # ['a', 'b']
h.has_key?('c') # false |
JS: | Object.keys(h); // ['a', 'b']
h.hasOwnProperty('c') // false |
取长度:
Ruby: | h.length # 2 |
JS: | Object.keys(h).length // 2 |
删除:
Ruby: | h.delete("b") |
JS: | delete h.b |
Functions: |
定义与调用:
Ruby: | #定义
def plus_5(num = 0) num + 5 end
#调用
plus_5 # 5
plus_5(10) # 15
[5, 10, 15].map { |k| plus_5(k) } # [10, 15, 20] |
JS: | //定义
function plus_5(num) { return (num || 0) + 5; }
//调用
plus_5(); // 5
plus_5(10); // 15
[5, 10, 15].map(plus_5); // [10, 15, 20] |
Math: |
Ruby: | [-5, -1, -8].max # -1
[-5, 15, 20].reduce(0, &:+) # 30 |
JS: | Math.max.apply(null, [-5, -1, -8]) // -1
[-5, 15, 20].reduce(function(sum, value) {
return sum + value;
}, 0) // 30 |
Random: |
Ruby: | prng = Random.new()
prng.rand(5..9) # one of [5, 6, 7, 8, 9] |
JS: | function rand(a, b) {
return Math.floor(Math.random() * (b-a+1)+a);
}
rand(5, 9); // one of [5, 6, 7, 8, 9] |
总结
总的简单来说,与javascript相比,ruby是纯面向对象语言,对局部变量的定义不用加前缀var,ruby对函数的定义不用function打头,而是def,在方法中不用括号,返回值直接写变量名,不用return,并且ruby代码中没有标点,看上去更加干净整洁。
参考http://agentcooper.github.io/js-ruby-comparison/
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。