ssnau / blog

1 stars 0 forks source link

Ruby #3

Open ssnau opened 7 years ago

ssnau commented 7 years ago

定义函数

def fact(n)
  if n == 0
    1
  else
    n * fact(n-1)
  end
end

class Person
  @@number_of_persons=0    # 类成员变量,以@@开头

  def initialize(id, name, addr)    # 构造函数,一但定义了构造函数,就需要以构造函数实例化
      @cust_id=id                   # 实例成员变量,以@开头
      @cust_name=name
      @cust_addr=addr
      @@number_of_persons = @@number_of_persons + 1
  end

  # 定义类级别方法(非实例方法),
  # 这样才可以让外界访问到类成员变量,
  # 否则Person.number_of_persons会报错
  def self.number_of_persons
    @@number_of_persons
  end

end

p = Person.new(1, 'jaic', 'no.888')   # 如果没有定义构造函数,则Person.new
puts p
puts Person.number_of_persons

对象相关

p.class           # p.constructor
p.superclass    # p.constructor.__proto__.constructor
p.is_a? P               # p instanceof Person
p.instance_of? P  # p instanceof Person && p.constructor === Person
p.methods     # Object.keys(p)
p.public_send("eql?", 3)  # p["eql?"](3) 或p.send("eql?", 3)
p.respond_to? "eql?"       # typeof p["eql?"]  === 'function'
p.to_s           # p.toString()
eval "x + 1"   # eval("x + 1")

Magical Method

class Sample
    def method_missing(key, *args)
        6666666
    end
end
s = Sample.new
puts s.not_found_hahahah    # output "6666666"

字面量

https://docs.ruby-lang.org/en/2.0.0/Hash.html

grades = { "Jane Doe" => 10, "Jim Doe" => 6 }
options = { :font_size => 10, :font_family => "Arial" }
options = { font_size: 10, font_family: "Arial" }
options[:font_size]  # => 10

arr = [1, 2, 3, 4, 5, 6]
arr[2]    #=> 3
arr[100]  #=> nil
arr[-3]   #=> 4
arr[2, 3] #=> [3, 4, 5]
arr[1..4] #=> [2, 3, 4, 5]
ssnau commented 7 years ago

匿名类

fred = Class.new do
  def meth1
    "hello"
  end
  def meth2
    "bye"
  end
end

a = fred.new     #=> #<#<Class:0x100381890>:0x100376b98>
a.meth1          #=> "hello"
a.meth2          #=> "bye"
ssnau commented 7 years ago

星号的意义

The * is the splat operator.

It expands an Array into a list of arguments, in this case a list of arguments to the Hash.[] method. (To be more precise, it expands any object that responds to to_ary/to_a, or to_a in Ruby 1.9.)

To illustrate, the following two statements are equal:

method arg1, arg2, arg3
method *[arg1, arg2, arg3]

It can also be used in a different context, to catch all remaining method arguments in a method definition. In that case, it does not expand, but combine:

def method2(*args)  # args will hold Array of all arguments
end
  1. 相当于js中的apply及concat的使用:
a.method *[1, 2, 3] # method.apply(a, [1,2,3])
arr = [*x]                 # arr = [].concat(x)
  1. 相当于js函数中的...args
def foo(a, *b)  # function foo(a, ...b) { ... }
  puts b
end

foo 3, 5, 6, 7  # [5,6,7]
ssnau commented 7 years ago

&操作符

link: http://stackoverflow.com/questions/1217088/what-does-mapname-mean-in-ruby

If foo is an object with a to_proc method, then you can pass it to a method as &foo, which will callfoo.to_proc and use that as the method's block.

The Symbol#to_proc method was originally added by ActiveSupport but has been integrated into Ruby 1.8.7. This is its implementation:

class Symbol
  def to_proc
    Proc.new do |obj, *args|
      obj.send self, *args  # 类似js中的obj[self].apply(obj, args) 
    end
  end
end
ssnau commented 7 years ago

各种操作符

%

x = %w(5 6 7)   # x = ['5', '6', '7']
x = %i(5 6 7)   # x = [:"5", :"6", :"7"]
x = %s(5 6 7)  # x = :"5 6 7"

=~

The=~ operator matches the regular expression against a string, and it returns either the offset of the match from the string if it is found, otherwise nil.

ruby-1.9.2-p136 :003 > /mi/ =~ "hi mike"
 => 3 
ruby-1.9.2-p136 :004 > "hi mike" =~ /mi/
 => 3 

ruby-1.9.2-p136 :005 > "mike" =~ /ruby/
 => nil 

ruby-1.9.2-p136 :005 > "ruby" =~ /ruby/
 => 0 

<=>

Perl was likely the first language to use it. Groovy is another language that supports it. Basically instead of returning 1 (true) or 0 (false) depending on whether the arguments are equal or unequal, the spaceship operator will return 1, 0, or −1 depending on the value of the left argument relative to the right argument.

a <=> b :=
  if a < b then return -1
  if a = b then return  0
  if a > b then return  1
  if a and b are not comparable then return nil

It's useful for sorting an array.

ssnau commented 7 years ago

RSpec

subjectit都有beforeEach的意思。区别在于subject会隐性赋值到subject变量上。