法
打印语句
print("hello,ruby") print('hello,\n ruby\n') print('hello,\'ruby\'') print('hello \\ ruby') puts("hello","ruby") puts("hello\n ruby")
puts("100") puts(100) p 100 p "100" p("hello \n ruby")
字符串操作
字符串长度:p “hello”.length P ‘hello’.size 字符串是否为空:p “”.empty? P ‘oo’.empty? 字符串删除:s.delete(str) s.delete!(str)
显示中文
ruby -Ks hello.txt print(1+2) print(1/2) print(1*2) print(1-2)
include Math print(sin(1))
注释
print("no") #print("ok") =begin print("begin") print("end") =end
控制语句 判断
if
a=20 if a>20 then print "bigger" elsif a==20 then print "equal" else print"smaller" end
a=20 if a>20 p "bigger" else if a==20 p "equal" else p "smaller" end end
a=10 if a>10 print "bigger" elsif a==10 print "equal" else print"smaller" end
unless a=10 b=20 unless a
=b" else print "a tag=["a","b","c"]
tag.each{|item| case item when "a" print "a" when "b" print "b" else print "c" end }
array=["aa",1,nil] item=array[1] case item when String puts "string" when Numeric puts "numeric" else puts "else" end
循环
i=1 while i<=10 print i,"\n" i+=1;
end
10.times{ print "hello\n" }
def hello print "hello ruby" end hello()
文件包含
require "hello" hello() 传参数 print "第一个实参",ARGV[0] num0=ARGV[0].to_i num1=ARGV[1].to_i print "num0-num1=",num0-num1
文件读取
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.close
变量
局部变量:以小写字母或“_”开头的变量 全局变量:以$开始的变量 实例变量:以@开始的变量 类变量:以@@开始的变量 虚拟变量:”true” “false” “self”等特定名称的变量
$x=0 x=0 require "one" p $x px
str1="foo" str2="f"+"o"+"o" p "str1.equal?(str2)" ,str1.equal?(str2) p str1.eql?(str2) p "str1==str2",str1==str2 效果类似 但是数值类比较重定义了该方法
p 1.0==1 p 1.0.eql?1
str1="foo" str2="f"+"o"+"o" p str1.object_id p str2.object_id
p "".empty? p "a".empty?() p /ruby/=~"hello,ruby" p /ruby/=~"hello"
函数
def hello(name="jia") print "welcome:"+name+"\n" end hello() hello("one")
def volume(x,y,z) return x*y*z end p volume(1,2,3)
省略 return 返回最后一行 def area(x,y,z) xy=x*y xz=x*z
yz=y*z (xy+xz+yz)*2 end p area(1,2,3)
def max(a,b) if a>b return a else return b end end p max(3,1)
ary=Array.new str="hello world" p ary.class
p str.class
ary=[] str="hello world" p ary.instance_of?(Array) p str.instance_of?(String)
str="hello world" p str.is_a?(String) p str.is_a?(Object)
类
类的三种定义方法
(1) class HelloWorld def HelloWorld.hello(name) print name,"said hello" end end HelloWorld.hello("ruby")
(2) class HelloWorld end class< said hello" end end HelloWorld.hello("ruby") (3) class HelloWorld def self.hello(name) print name+":said hello" end end HelloWorld.hello("ruby")
类方法引用
类.方法 类: :方法
常数
class Hello Version="1.0" end p Hello::Version
类变量
class Hello @@count=0 def Hello.count @@count end def initialize(name="ruby") @name=name end def hello @@count+=1; print @name+":hello\n" end end
tom=Hello.new("tom") jim=Hello.new("jim") ruby=Hello.new
p Hello.count tom.hello jim.hello ruby.hello p Hello.count
字符串类 ‘’与 的区别 ‘’与””的区别
moji="字