当前位置: 代码迷 >> Ruby/Rails >> ruby学习笔记二
  详细解决方案

ruby学习笔记二

热度:137   发布时间:2016-04-29 02:22:51.0
ruby学习笔记2

ruby学习笔记2

?

  1. 构造方法initialize

Ruby创建对象时通过Ruby.new方法,若传递参数实际上是传递给了initialize方法

?

class Test

? def initialize(name,age,phone)

? ? @name = name

? ? @age = age

? ? @phone = phone

? end

end

调用:Test.new('zhangsan',20,'18112345678')

也可以给参数添加默认值

class Test

? def initialize(name='kk',age=18,phone='18112345678')

? ? @name = name

? ? @age = age

? ? @phone = phone

? end

end

?

调用:

test = Test.new

p test

?

输出

#<Test:0x000001023a2fe8 @name="kk", @age=18, @phone="18112345678">

?

没有给默认值的参数必传,否则报错。若只有部分参数给了默认值,在调用的时候只传递了未有默认值的参数,会依序赋值。

class Test

? def initialize(name,age=18,phone)

? ? @name = name

? ? @age = age

? ? @phone = phone

? end

end

调用:

p Test.new('kk','18112345678')

输出:

#<Test:0x0000010208e7a8 @name="kk", @age=18, @phone="18112345678">

?

2、to_s方法,inspect方法

to_s类似java中的toString,默认输出对象名及内存ID,可以重写。

重写之前调用:Test.new.to_s

输出:

#<Test:0x00000101cc5630>

?

重写:

class Test

? def initialize(name='kk',age=18,phone='18112345678')

? ? @name = name

? ? @age = age

? ? @phone = phone

? end

? def to_s

? ? "myname is [email protected]} , [email protected]} years old, telphone:[email protected] call me latter!"

? end

end

?

调用:

Test.new.to_s

Test.new.inspect

输出:

?myname is kk , 18 years old, telphone:18112345678.please call me latter!

#<Test:0x000001024d3c78 @name="kk", @age=18, @phone="18112345678">

3、print、puts、p与to_s、inspect的关联

user = Test.new

print user ?-------> 将调用输出user.to_s

puts user ? -------> 将调用输出user.to_s

p user ? ? ? -------> 将调用输出user.inspect

?

?

?

?