ruby1.8到2.1語法改變

c3tc3tc3t發表於2015-12-12

1定義hash的語法改變
old_way = {:foo => "bar", :one => 1}
new_way = {foo: "bar", one: 1}


2 方法中傳遞hash

def some_method(hash = {})
# do stuff
end
some_method(:foo => "bar")
some_method(foo: "bar")

3 hash中key做引數

# OLD
def old_way(options={})
return options[:foo]
end

 

old_way(:foo => "bar") # => "bar"
old_way #=>nil

 

# NEW UNNAMED KEYWORD ARGUMENTS
def new_way(**options)
return options[:foo]
end
# => :new_way


new_way(foo: "bar" ) # => "bar"
new_way b# => nil

hash中的key可以作為預設的方法引數
# NEW NAMED KEYWORD ARGUMENTS
def new_way(foo:)
return foo
end
# => :new_way


new_way(foo: "bar") # => "bar"
new_way # ArgumentError: missing keyword: foo

定義proc的新語法

old_way = Proc.new { |a, b| a + b }
old_way.call(1, 2)
# => 3


new_way = ->(a, b) { a + b }
new_way.call(1, 2)
# => 3

生成符號陣列

old_way = [:foo, :bar, :baz]
new_way = %i(foo bar baz)

定義有理數方法
old_way = Rational(6, 5)
new_way = 1.2r

關鍵字引數

def foo(a, b="b_default", *c, d:, e: "e_default", **f, &g)
# do stuff
end
a: 必須有的引數
b:可選的引數有一個預設值
c: 通常接受多個引數存為陣列
d: 關鍵字引數
e:關鍵字引數有預設值
f:接收引數存為hash
g:塊引數

相關文章