zoukankan      html  css  js  c++  java
  • ruby1.8到2.1语法改变

    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:块参数

  • 相关阅读:
    9-15
    9-5
    8-26
    8-24
    7-20
    7-17
    我离职后要干些什么
    6-18
    5-28
    5-20
  • 原文地址:https://www.cnblogs.com/or2-/p/5041823.html
Copyright © 2011-2022 走看看