Open ssnau opened 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"
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
a.method *[1, 2, 3] # method.apply(a, [1,2,3])
arr = [*x] # arr = [].concat(x)
...args
def foo(a, *b) # function foo(a, ...b) { ... }
puts b
end
foo 3, 5, 6, 7 # [5,6,7]
&
操作符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_pro
c 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
%
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.
subject
和it
都有beforeEach
的意思。区别在于subject
会隐性赋值到subject
变量上。
定义函数
类
对象相关
Magical Method
字面量
https://docs.ruby-lang.org/en/2.0.0/Hash.html