Ruby常用语法

2019-06-06  本文已影响0人  Bruce钟

Ruby语法简单一致,大多已经烂熟于心,这里只列出偶尔用到的语法

一些要点

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

上一篇 下一篇

猜你喜欢

热点阅读