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

ruby注意点

2016-05-23 23:35 316 查看
1、强类型,即不会自动进行类型转换,而C/C++为弱类型。


# Ruby
i = 1
puts "Value is " + i

# TypeError: can't convert Fixnum into String
#   from (irb):2:in `+'
#   from (irb):2


2、完全地OO(Object-Oriented面向对象),所有方法都是对对象,无全局函数。


strlen(“test”)   # error

“test”.length



3、变量:以小写开头。 my_composer = ‘Beethoven’

4、类型转换: puts 2.to_s + ‘5’ #25

5、常量:以大写开头。 Foo = 1

6、空值nil。

7、字符串符号symbols,相同符号不会重复创建对象。 puts :foobar.object_id

8、队列Array。


a = [1, ‘cat’, 3.14 ]

puts a.inspect # 输出 [1, ‘cat’, 3.14]

# inspect将对象转换成适合阅读的字符串

# 读取没有设定的元素,则值为nil

a = [‘Ruby’, ‘Python’]

a.each do |ele|

puts ‘I love ’ + ele + ‘!’

end

# I love Ruby!

# I love Python!


9、Hash类似C++的map和python的Dict,使用Key-Value结构。通常使用Symbol当作Key:


config = { :foo => 123, :bar => 456 }

config = { for: 123, bar:456 } # 和上面等价,Ruby 1.9新语法

puts config[:foo]  #123

puts config[“nothing”]  #nil


10、else if写成elsif:


total = 26000

if total > 100000
puts "large account"
elsif total > 25000
puts "medium account"
else
puts "small account"
end

puts “greater than ten” if total > 10 # 适合执行的if语句只有一行的情况


11、Case结构,case when:


case name
when "John"
puts "Howdy John!"
when "Ryan"
puts "Whatz up Ryan!"
else
puts "Hi #{name}!"
end


12、while,until,loop,next,break和C++语法不同,不过很少用,实际用迭代器。

13、正则表达式:


# 找出手机号码
phone = "123-456-7890"
if phone =~ /(\d{3})-(\d{3})-(\d{4})/
ext  = $1
city = $2
num  = $3
end


14、?与!的惯用法:方法名称用?标识返回Boolean值,用!标识有副作用,如array.sort!

15、自定义类型:


class Person # 大写开头的常數

puts “running when class loaded” # 载入该类型时执行,主要用来做Meta-programming

@@sname = ‘Class var’# 类变量

def initialize(name) # 构建函数
@name = name       # 对象变量
end

def say(word)
puts "#{word}, #{@name}" # 字符串相加
end

end

p1 = Person.new("ihower")
p2 = Person.new("ihover")


16、类继承,使用<符号。

17、Module和Class类似,但是不能用new来创建,其用途一是可以当作Namespace,更重要的功能是Mixins,将一个Module混入类型中,这样这个类型就拥有了此Module的方法,多重继承的问题也通过Module来解决。


首先是debug.rb

module Debug
def who_am_i?
puts "#{self.class.name}: #{self.inspect}"
end
end

然后是foobar.rb

require "./debug"
class Foo
include Debug # 这个动作叫做 Mixin
end

class Bar
include Debug
end

f = Foo.new
b = Bar.new
f.who_am_i? # 输出 Foo: #<Foo:0x00000102829170>
b.who_am_i? # 输出 Bar: #<Bar:0x00000102825b88>


18、异常处理,使用rescue、ensure:


begin
puts 10 / 0 # 这会抛出 ZeroDivisionError 的异常
rescue => e
puts e.class # 如果发生异常会执行 rescue 这一段
ensure
# 无论有沒有发生异常,ensure 这一段都一定会执行
end
# 输出 ZeroDivisionError


其它高阶功能如Meta-programming暂不考虑。


参考转载文档:https://ihower.tw/rails4/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: