Ruby中的p和puts的使用区别浅析
p 和 puts 是 Ruby 中特别常用的方法,很多童鞋可能认为它们是差不多的,使用的时候也不加注意,但是仔细考究起来,它们是有明显差别的
先举一个例子:
class Foo
def inspect
“foo from inspect”
end
def to_s
“foo from to_s”
end
foo=Foo.new
p foo
puts foo
p”p:<#{foo}>”
puts”p<#{foo}>”
classCalculator
def add num1, num2
num1+num2
end
end
用于测试Calculator类的add方法的feature文件如下:
Feature: Unit testforCalculator
Scenario: Add two numbers
Given I have a calculator created
WhenI add '3' and '5'
ThenI should get the result of '8'
对应的step文件为:
1require File.join(File.dirname(__FILE__), "../calculator")
2require 'rspec'
3
4Given /^I have a calculator created$/do
5@calculator = Calculator.new #新建一个@calculator实例变量
6end
7
8When/^I add '([^"]*)' and '([^"]*)'$/do|num1, num2|#捕捉2个参数
9@result = @calculator.add(num1.to_i, num2.to_i)#完成两个数相加(3+5)
10end
11
12Then/^I should get the result of '([^"]*)'$/ do |expected_result| 13@result.should == expected_result.to_i#t转为整数型展示
14end
1Feature: Unit testforCalculator
2
3Scenario: Add two numbers # features/Calculator.feature:4
4Given I have a calculator created # features/step_definitions/calculator_step.rb:4
5WhenI add '3' and '5' # features/step_definitions/calculator_step.rb:8
6ThenI should get the result of '8' # features/step_definitions/calculator_step.rb:12
7
81 scenario (1 passed)
93 steps (3 passed)
100m0.002s
---------------------------------------------------------------------------
self与self class用法上的区别
self指对象本身,[self class]返回的是类,打印出来就相当于类名。静态方法的调用就是类名加方法
——————————————————