您的位置:首页 > 编程语言 > Ruby

[ruby on rails] 深入(2) ruby基本语法

2014-12-05 12:11 411 查看

1. 调试&注释&打印输出

1.1 调试

ruby属于解释型语言,即脚本,在linux上,脚本的执行无非三种:

1. 用解释器运行脚本

解释器  脚本文件


即:ruby 脚本文件

2. 直接运行脚本

在脚本文件里面用

#! 脚本解释器


定义好脚本解释器路径,然后再授予脚本执行权限,接着直接运行

./脚本文件


即可。

3. 在解释器里面运行脚本

root@tommy:/home/ywt/ror_tests/ruby_tests# irb
2.1.5 :001 > str = "sdfsdf"
=> "sdfsdf"
2.1.5 :002 > puts str
sdfsdf
=> nil
2.1.5 :003 > print str
sdfsdf => nil
2.1.5 :004 >


ps:建议直接用第一种,第二种比较麻烦,第三种比较难看(当然try语法可以用这个)

1.2 注释

coment.rb

#single line comment
str = 'hello world'
=begin
this is a test of
mutiple line comments
=end
puts str


测试输出如下:

root@tommy:/home/ywt/ror_tests/ruby_tests# ruby comment.rb
hello world


即:

#单行注释


=begin
多行注释
=end


1.3 打印输出

print_test.rb

str ='hello world'
puts str
print str
puts ' ========='


测试输出

root@tommy:/home/ywt/ror_tests/ruby_tests# ruby print_test.rb
hello world
hello world =========


即:

puts  str  =  print str  + print new_line


(new_line在windows下面是 '\r\n' ,linux上面是 '\n')

2类

2.1 一般定义

class Aclass
end


注意:类名的第一个字母必须大写!(python则无此要求)

2.2 继承的一般定义

class Child<Father
end


即继承符为'<';

问题:是否支持多继承?

2.3成员

2.3.1 成员变量

attr_accessor :成员变量


例如Cat类的定义

class Cat
attr_accessor :name
attr_accessor :age
attr_accessor :sex
def to_s
"#{@name},age #{@age},#{@sex}"
end
end

c = Cat.new
c.name='ruby'
c.age=1
c.sex='female'
puts c


  

测试:

root@tommy:/home/ywt/ror_tests/ruby_tests# ruby class_cat.rb
ruby,age 1,female


  

2.3.2 成员函数

成员函数定义

def method
codes
data
end


最后的data是返回的数据,可以不用写return ; codes是实际的代码。

问题,成员函数如何接受参数?直接定义就好了,如下:

def method(arg1,arg2,arg3...)
codes
data
end


对于返回值为bool类型的函数,可以如下定义

def method?
codes
true/false
end


2.3.3 构造函数

def initialize(arg1,arg2,arg3..)
codes
end


  

例如上面的Cat类,改造如下:

class Cat
attr_accessor :name
attr_accessor :age
attr_accessor :sex
def initialize(name,age,sex)
@name = name
@age = age
@sex = sex
end

def to_s
"#{@name},age #{@age},#{@sex}"
end

def say_hi(name)
puts 'hi '+name
end
end

c = Cat.new('ruby',1,'female')
puts c
c.say_hi 'alice'


测试输出:

root@tommy:/home/ywt/ror_tests/ruby_tests# ruby class_cat.rb
ruby,age 1,femalehi alice


2.3.4 类变量&self操作符

@@类变量


类属性定义如下,需要有self操作符:

def self.类变量
@@类变量end


demo如下:

class Pro
@@name1 = 'color'
def self.name2
@@name1
end
end

puts Pro.name2


测试:

root@tommy:/home/ywt/ror_tests/ruby_tests# ruby test_property.rb
color


self,类似于python里面的self,指向当前的变量实例。不同的是ruby的self可以用在修饰类属性上。

3. 数据类型

3.1 字符串

定义

"字符串"


单引号,原始字符串(类似于python中 r'字符串',c#中 @'字符串'),之所以这样,因为它是literal by literal方式的显示。

'字符串'


demo:

2.1.5 :006 > x = 12
=> 12
2.1.5 :007 > puts "x = #{x}"
x = 12
=> nil
2.1.5 :008 > puts 'x=#{x}'
x=#{x}
=> nil


常用函数: upcase /downcase /reverse/count, demo如下

2.1.5 :010 > str = "an apple a day keeps the doctor away"
=> "an apple a day keeps the doctor away"
2.1.5 :011 > puts str.upcase
AN APPLE A DAY KEEPS THE DOCTOR AWAY
=> nil
2.1.5 :012 > puts str.capitalize
An apple a day keeps the doctor away
=> nil
2.1.5 :013 > puts str.size
36
=> nil
2.1.5 :014 > puts str.count "an"
7
=> nil
2.1.5 :015 > puts str.upcase!
AN APPLE A DAY KEEPS THE DOCTOR AWAY
=> nil
2.1.5 :016 > puts str
AN APPLE A DAY KEEPS THE DOCTOR AWAY
=> nil
2.1.5 :017 > puts str.downcase
an apple a day keeps the doctor away
=> nil
2.1.5 :018 > puts str.reverse
YAWA ROTCOD EHT SPEEK YAD A ELPPA NA
=> nil


官方参考文档:http://ruby-doc.org/core-2.1.5/String.html  

 

3.2 数值

三种类型:Fixnum/Bignum/Float ,如下:

2.1.5 :029 > 100.class
=> Fixnum
2.1.5 :030 > 100000000000000.class
=> Bignum
2.1.5 :031 > 1.0.class
=> Float


默认的类型转换

num op Float = Float

num op num = num

Float op Float = Float

op指: +-*/ % , 如下:

2.1.5 :035 > (1+2.0).class
=> Float
2.1.5 :036 > (1/100).class
=> Fixnum
2.1.5 :037 > (2.0/2.0).class
=> Float


常用函数:

整形:odd,even,abs

浮点型:round, numerator(分子部分), denominator(分母部分数值)

2.1.5 :038 > 11.odd?
=> true
2.1.5 :039 > 11.even?
=> false
2.1.5 :040 > -12.abs
=> 12
2.1.5 :041 > 12.12341234.round(2)
=> 12.12
2.1.5 :042 > 0.75.numerator
=> 3
2.1.5 :043 > 0.75.denominator
=> 4


更多api请看这里:http://ruby-doc.org/core-2.1.5/Integer.html

3.3 数组

2.1.5 :077 > arr=["adsad",1,2,3,"21123",123.123]
=> ["adsad", 1, 2, 3, "21123", 123.123]
2.1.5 :078 > puts arr
adsad
1
2
3
21123
123.123
=> nil
2.1.5 :079 > arr[-1]
=> 123.123
2.1.5 :081 > arr[2,4]
=> [2, 3, "21123", 123.123]
2.1.5 :082 > arr[2..4]
=> [2, 3, "21123"]
2.1.5 :091 > def ret_arr
2.1.5 :092?>   return 1,2,4
2.1.5 :093?>   end
=> :ret_arr
2.1.5 :094 > ret_arr
=> [1, 2, 4]


  

元素支持任何类型,可以通过arr[index]方式进行索引(index可以为负),支持切片,支持不带括号返回数组。

行为跟python的数组极其相似。

常用方法:map(支持写入 map!),each,select(等同于python里面的filter,map跟python里面的map等同),find_all(间接等于select)

2.1.5 :158 > names = ['alice','Bob','carl','dMitri']
=> ["alice", "Bob", "carl", "dMitri"]
2.1.5 :160 > puts names.map{|n| n.capitalize}
Alice
Bob
Carl
Dmitri
=> nil


2.1.5 :162 > names.each{|n| puts "#{n} is here"}
alice is here
Bob is here
carl is here
dMitri is here
=> ["alice", "Bob", "carl", "dMitri"]


2.1.5 :171 > arr.map{|n| n*2+5}
=> [7, 9, 11]
2.1.5 :172 > arr.find_all {|n| n>2}
=> [3]

 2.1.5 :176 > arr.select {|n| n>2}
=> [3]

更多用法参考这里:http://ruby-doc.org/core-2.1.5/Array.html

3.4 哈希类型(键值类型)

跟python里面的dict是一个概念。

定义方法:

{:var1 => val1 , var2 => val2 ,...}


也可以这样定义:

{var1:val1, var2,val2, ...}


php风格和python风格。demo如下

2.1.5 :100 > d = {name:'jone', age:38}
=> {:name=>"jone", :age=>38}
2.1.5 :101 > puts d[:name]
jone
=> nil
2.1.5 :103 > d[:name]="alice"
=> "alice"
2.1.5 :105 > puts d
{:name=>"alice", :age=>38}
=> nil
2.1.5 :106 > d.has_key?(:name)
=> true


感觉使用起来没有python顺手。

3.5 总结

数据类型的设计上比较简洁: 整形/浮点型/数组/哈希类型

所有的数值都是对象。拥有对象的方法。

4. 流程控制

4.1 条件跳转

if & unless

if condition
elseif condition
else
end


unless condition
end


unless = if not

case

case var
when val then codes
else codes
end


demo

2.1.5 :121 > x=1
=> 1
2.1.5 :122 > case x
2.1.5 :123?>   when 3 then puts 'X is three'
2.1.5 :124?>   when String then puts "X is a string"
2.1.5 :125?>   when 0..2 then puts "X is 0, 1 or 2"
2.1.5 :126?>   else puts "X is something else"
2.1.5 :127?>   end
X is 0, 1 or 2
=> nil


4.2 循环

while/until

while/util condition
codes
end


times loop

执行num次

num.times do
codes
end


没有for/foreach

5 数组/哈希类型遍历

5.1 数组遍历

数组.each do |当前index对应的变量别名|
codes
end


或者

数组.each{|当前index对应的变量的别名| codes}


或者

数组.map{|当前index对应的变量的别名| codes} #不改变原数据
数组.map!{|当前index对应的变量的别名| codes} #改变原数据


5.2 哈希遍历

哈希类型变量.each do |key的别名, value的别名|
codes
end


demo

2.1.5 :144 > arr=[1,2,3]
=> [1, 2, 3]
2.1.5 :145 > dict={name:'john',age:38}
=> {:name=>"john", :age=>38}
2.1.5 :146 > arr.each do |v|
2.1.5 :147 >     puts v+1
2.1.5 :148?>   end
2
3
4
=> [1, 2, 3]
2.1.5 :155 > dict.each do |k,v|
2.1.5 :156 >     puts "#{k} is #{v}"
2.1.5 :157?>   end
name is john
age is 38
=> {:name=>"john", :age=>38}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: