Ruby语法简单一致,大多已经烂熟于心,这里只列出偶尔用到的语法
一些要点
- Ruby 中变量、表达式 值的真假: nil/false 为假,其他为真, 这点与很多语言不同,与lisp一致。
Switch 语法
case "str"
when /^s/, "abc"
puts "match one"
when /r$/ then puts "one line statement"
else
puts "otherwise"
end
Ruby-Doc/syntax/control_expressions
遍历
遍历 数组、哈希、Range
arr = [ 1, 2, 3 ]
hash = { a: 1, b: 2, c: 3 }
arr.each { |v| puts v } # 遍历数组
hash.each { |k,v| puts k, v } # 遍历hash
hash.keys.each { |k| puts k } # 遍历hash keys
Map Reduce
(1..5).map{ |v| v*v }.reduce(:+) # 1 + 4 + 9 + 16 + 25
(1..5).select{ |v| v % 2 == 0 }.reduce(:*) # 2 * 4
猴子补丁
不懂猴子补丁的google一下
class Integer
def power(n)
n.times.reduce(1){ |s| s *= self }
end
end
5.power(3) # 5*5*5 = 125
对比Python
简单推导
对比python的简单推导,ruby更加简单直观,更面向对象
[ x*2 for x in range(1,4) ] #=> [2,4,6]
[ [x,x*2] for x in range(1,4) ] #=> [ [1,2], [2,4], [3,6] ]
{ x: x*2 for x in range(1,4) } #=> { 1: 2, 2: 4, 3: 6 }
( x*2 for x in range(1,4) ) #=> generator of (2,4,6)
(1..3).map{ |v| v*2 } # => [2,4,6]
(1..3).map{ |v| [v,v*2] } # => [[1,2],[2,4],[3,6]]
(1..3).map{ |v| [v,v*2] }.to_h # => {1=>2, 2=>4,3=>6}
(1..3).map{ |v| v*2 }.each # Enumerator of [2,4,6]
引用其他脚本
多脚本组成的工具时用得上
require File.expand_path('../rblib/mytool', __FILE__) # recommanded
load File.expand_path('../rblib/mytool.rb', __FILE__)
require 能更好的处理重复加载的情况
d
网友评论