函数的括号可有可无,如puts("xxxx")或puts "xxxx",为避免使用歧义,最好使用括号;在不影响函数使用的情况下可以去掉括号。
语句末尾的分号可有可无,一行语句有多个语句时要用分号隔开。
只有nil和false是假,其他都是真。
简单输出
puts直接输出一行内容,包括回车换行;
print输出字符串,但是不包含回车换行;
printf可带占位符输出;
puts 'hello world'
print '1111'
print '2222'
printf "\n-->%s","Yes, that's right";
简单输入
gets获取输入字符串
print 'Enter you name'
name = gets()
puts "Hello #{name}"
字符串及其内嵌值
在字符串中嵌入#{xxx},则是对xxx求值,xxx是语句块,可以是单个变量也可以是表达式,对xxx整体求值后再嵌入到字符串中。
puts "Hello #{name}"
puts "\n\t#{(1+2)*3} Goodbye"
简单条件语句
and,or,not,&&,||,!,都是连接词,then关键字可有可无,但是在将if语句写成一行时则必须添加then,用于隔开“条件”和”结果“;
if 11<22
puts "11<22"
end
if 11<22 then puts "11<22" end
if a<b then
puts "a<b"
else
puts "a>b"
end
a=1;b=2;c=3;d=4;e=5;f=6;g=nil
if a<b and c<d or e<f and not g then
puts "good"
end
if a<b && c<d || e<f && !g then
puts "good"end
end
局部变量和全局变量
$xxx用于表示全局变量,其他都是局部变量;
全局变量的作用域是整个文件,包括require的文件(作用域可以跨文件),都可以对全局变量进行修改;
局部变量的作用域在它的上下文,如果在函数中则仅限于该函数中,如果在函数外则限于该文件中,最多限于该文件中,其他文件不能引用;(待续。。。)
localvar = "hello"
$globalvar = "goodbye"
实例变量
@xxx是实例变量,即类的实例变量,是类私有变量。
class Dog
def set_name(aNmae)
@myname = aName
end
def get_name
return @myname
end
end
mydog=Dog.new
mydog.set_name('Fido')
mydog.set_name 'Fido'
puts mydog.get_name
inspect函数
Ruby中所有的对象都有inspect函数,该函数返回对这个对象的描述,例如string对象的值,类对象的值;
p函数,效用同inspect函数,但是不属于任何对象,相当于是全局函数,p(xxx)等价于puts xxx.inspect;
puts mydog.inspect
p(mydog)
p(100)
puts 100.inspect
p(100.to_s)
待续。。。