初学者Ruby笔记
1 . 在ruby中,你所操作的一切都是对象,操作的结果也是对象;Tcl操作的结果都是String类型. tcl不支持.net中的形如int , double ,char等等类型,唯一支持的就是string类型
2 . 类的定义要在class..end之间,类名必须以大写字母开始,也就是说类名要是个常量.
3. 若某个类已经被定义过,此时又用相同的类名进行类定义的话,就意味着对原有的类的定义进行追加
例如: class Test
def test
puts "test"
end
end
class Test
def test1
puts "test1"
end
end
对于Test类的方法,先定义test后定义test1,两者都可用.
4. 特殊变量可以用{}来求值,如#{},全局变量以$开头,类变量以@@开头,且必须初始化,实例变量以@开头。
5. " <=>" 方法通常意思为比较,返回值为-1,0或1分别表示小于,等于和大于. 如: 3<=>4 返回 -1,4<=>3返回 1
6. 方法名应该以小写字母开始,如果你使用大写字母开始,Ruby解释器会认为它是一个常量,这样可能会带来名称解析错误
如: def Test
p "test"
end
运行 p Test ,会报 uninitialized constant Xgg.
7.一般的编写习惯是如果方法含有参数,那么就使用圆括号将参数括起来,否则不需要圆括号.
8.当定义一个方法后,可以用undef_method取消一个方法的定义,貌似运用的不多。
class Test
def test
p "test2"
end
end
obj1 = Test.new
obj1.test
#会输出"test2"
class Test
undef_method(:test)
end
obj1.test
#会提示方法没有被定义
9.继承,用<表示 ,ruby语言只支持单继承,每一个类都只能有一个直接父类。
class Student < Person
def initialize(name, gender, age, school)
@name = name
@gender = gender
@age = age
@school = school
end
end
10.特殊方法是指某实例所特有的方法。
class << obj
……
end
obj是一个具体的对象实例,class << 代表它的特殊类
11.interator迭代器。。
6.times{|i| p i} 求出0-6之间的数
2.times {
p defined?(num)
num =10
p num
}
#会输出 nil 10 nil 10
["ab","ced"].each {|entity| p entity}
12. yield
def callBlock
yield
yield
end
callBlock {p "In the block"}
#输出: In the block In the block
14.ruby中求小数 如:format("%0.2f",11.329)-->11.33
ruby按精度保留小数
有一个round函数,用起来非常方便:
>> 2.3465.round "\n 换行"
=> 2
>> 2.3465.round(2)
=> 2.35
>> 2.3465.round(3)
=> 2.347
15.对象的initialize
class Song
def initialize(name, artist, duration)
@name =name
@artist = artist
@duration =duration
end
end
song = Song.new("Bicy","Fleck",260)
song.inspect(inspect方法返回一个文字表征的字符串)
16.可以直接引入Math对象 include Math -16.abs
17.单行注释用#,多行注释用 =begin **** =end,也可以用多个#
18.文件读取文件读取文件读取文件读取
filename="C:\\Users\\Administrator\\Desktop\\ruby\\one.txt"
file=open(filename)
text=file.read
print text
file.close
filename=ARGV[0]
file=open(filename)
while text=file.gets
print text
end
file.clos
19.类方法引用
类.方法 类::方法
20.‘ ’与""的区别
moji="字符串"
str="这也是#{moji}"
p str
str1='这也是#{moji}'
p str1
21.设置字符编码
before_filter :set_charset
def set_charset
@headers["Content-Type"] = "text/html; charset=utf-8"
end