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
相关文档:
在使用中ruby的过程中难免会遇到提高性能的问题,由此便想起了ruby线程。但是我在使用中却发现ruby的线程却不能提高性能。我写了以下代码,做了些简单测试。
代码
# -*- coding: GB2312 -*-
require 'date'
# 使用线程,线程的处理代码里没有sleep
def have_thread_no_sleep
p Time.now
thread1 = Thread.new do
......
照例可以先看端程序
class Person
def initialize( name,age=18 )
@name = name
@age = age
@motherland = "China"
end
def talk
puts "my name is "+@name+", age is "+@age.to_s
&n ......
irb 是从命令行运行的
irb 的命令行选项(摘自 Porgramming Ruby 第二版)
-f
禁止读取~/.irbrc Suppress reading ~/.irbrc.
-m
数学模式(支持分数和矩阵) Math mode (fraction and matrix support is available).
-d
设置#DEBUG为true(同ruby -d一样) Set $DEBUG to true (same as ``ruby -d'').
-r lo ......
从命令行启动Ruby解释器时,你不仅可以提供程序文件的名字,而且可以提供一个或多个命令行开关。你选择的开关指示解释器以一种特定的方式运转,并且/或者执行特定的操作。
Ruby命令行开关有20多个,其中有些很少使用,有些则每天被很多Ruby程序员使用。在这里我们将再看几个最常用的。(你已经看到过其中的两个,-c和&ndas ......
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 ......