Ruby学习笔记三——类
#一、定义一个类
class Person
def initialize(name,age=18)
@name=name;
@age=age;
@motherland="china";
end
def talk
puts "my name is "+@name+" and I am "+@age.to_s
if @motherland == "china"
puts "I am a Chinese."
else
puts "I am a foreigner."
end
end#talk结束
attr_writer:motherland
attr_writer:age
end#class结束
p1=Person.new("Zhangren",10);
p1.talk;
p1.motherland="abc";
p1.talk;
p1.age=20;
p1.talk;
#二、继承自一个类
class Student < Person
def talk
#super;#这会调用父类talk中的代码
puts "I am a student. my name is "+@name+", age is "+@age.to_s
end # talk方法结束
end # Student类结束
p3=Student.new("kaichuan",25); p3.talk
p4=Student.new("Ben"); p4.talk
#Ruby没有重载方法,因为参数没有类型,所以没法重载。有多态,不过不太明显,因为变量都没有类型,所以谈不上父类引用指向子类对象,都是统一的引用。
#三、变量动态性
# E5.3-1.rb
a=5
b="hh"
puts "a = #{a} #{b} #{a}"
puts "b = #{b}"
#四、重写
def talk (a,b=1)
puts "This is talk version 2."
end
def talk (a)
puts "This is talk version 1."
end
talk (2) # This is talk version 1.
#talk (2,7) # 报错,因为重写之后,只有后一个有用,没有重载。父子类中也是重写。
#五、Ruby的变量等标识名称区分太小写。全局变量用$引用,实例变量用@(也就是成员变量,因为不需要声明,都是直接用),类变量用@@(其实就相当于静态变量)
$a="\n a is a global value"
puts $a
class StudentClass
@@count=0
def initialize( name )
@name = name
@@count+=1
end
def talk
puts "I am #@name, This class have #@@count students."
end
end
p1=StudentClass.new("Student 1 ")
p2=StudentClass.new
相关文档:
1. ruby已成为1.87
2. 必须先安装安装光盘里的新的xcode,在"optional"目录里
3. 可能需要重新安装macport
http://trac.macports.org/wiki/Migration
4. 或者升级macport
http://weblog.rubyonrails.org/2009/8/30/upgrading-to-snow-leopard
$ sudo port selfupdate
$ sudo port sync
$ sudo port upgrade --force insta ......
原文连接: http://hi.baidu.com/%B7%CF%B2%C5%CB%FB%B8%E7/blog/item/09c19411244152daf7039ec4.html
通过命令行查看ruby版本信息:
ruby -v
命令行运行程序:
方法1.
ruby -e 'print "hello ruby"'
-e 表示将后面的一行作为ruby程序
print 是ruby的一个内置函数
方法2.交互编译环境
irb (命令行输入后, ......
http://www.gayathri-frenzy.com/technology/ruby-on-rails
I kept thinking for a while on what do I have next in the store
Here we go “Ruby on Rails”
Ruby on Rails, often shortened to Rails or RoR, is an open source web application framework for the Ruby Programming language.Ruby is a ......
#一、数组引用
arr=[3,4,5,6,7,8,9]
puts arr[0] #3
puts arr.first #3
puts arr[arr.length-1] #9
puts arr[arr.size-1] #9
puts arr.last #9
puts arr[-1] #9
puts arr[-2] #8
print arr[1..3] ,"\n" #456
print arr[-3,4] ,"\n" #789,从-3开始 ,打印4个元素,这里只有三个
#Ruby的数组大小是动态的,你能够 ......