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

ruby基础总结(二)

2015-10-28 18:28 465 查看
#类变量
#类变量是该类所有实例的共享变量
#从类的外部访问类变量时需要存取器
class HelloCount
@@count = 0

def HelloCount.count
@@count
end

def initialize(myname = "ruby")
@name = myname
end

def hello
@@count += 1
puts "hello,world. i am #{@name}.\n"
end
end

bob = HelloCount.new("bob")
alice = HelloCount.new("alice")
ruby = HelloCount.new

puts HelloCount.count
bob.hello
alice.hello
ruby.hello
puts HelloCount.count

#范围运算符
p (1..10).to_a
p (1...10).to_a

#异常处理
#ex.class
#ex.message
#ex.backtrace
begin
a = 10
rescue ex
p ex.message
end

#array sort
array = ["ruby","perl","php","python"]
sorted = array.sort{|a , b| a <=> b}
p sorted

sorted = array.sort{|a , b| a.length <=> b.length}
p sorted

#定义带块的方法
def myloop
while true
yield
end
end

#传递块参数,获取块的值
def total(from,to)
result = 0
from.upto(to) do |num|
if block_given?
result += yield(num)
else
result += num
end
end
return result
end

p total(1,10)
p total(1,10){|num| num**2}

hash = {a: 100,b: 200,c: 300}
hash.each_with_index do |(k,v),index|
p [k,v,index]
end
p hash[:a]

#proc 对象是能让块作为对象在程序中使用的类
hello = Proc.new do |name|
puts "hello,#{name}"
end

hello.call("world")
hello.call("ruby")

def total2(from,to,&block)
result = 0
from.upto(to) do |num|
if block
result += block.call(num)
else
result += num
end
end
return result
end

p total2(1,10)
p total2(1,10){|num| num ** 2}

#将Proc对象作为块传给其他方法处理
def call_each(ary,&block)
ary.each(&block)
end

call_each [1,2,3] do |item|
p item
end

#局部变量与块变量
x = 1
y = 1
ary = [1,2,3]

ary.each do |x|
y = x
end

p [ x,y ]

#Numeric 数值类
def fact(n)
if n <= 1
1
else
n * fact(n-1)
end
end

p fact(20)

#rational /分数/
p Rational(2,3).to_f.ceil

=begin
to_f转换为float
to_i转换为int
round方法四舍五入
ceil最小整数
floor最大整数
to_r转为Rational
to_c转为Complex
=end

#随机数
p Random.rand
p Random.rand(100)

#计数
=begin
n.times
from.upto(to)
from.downto(to)
from.step(to,step)
=end

#数组类
#数组的创建方法
name = ["tang","xue"]
puts name[0]

name.each do |name|
puts name
end

=begin
Array类情况下,
若new 方法没有参数,则会创建元素个数为0的数组,
若new方法只有1个参数,则会创建参数个元素的数组,这些元素都为nil
若new方法有俩个参数,则会创建first参数个数元素的数组,这些元素的值都为second参数
=end
name = Array.new
p name
name = Array.new(5)
p name
name = Array.new(5,"tangxuelong")
p name

#使用%w 与 %i
#创建不包含空白的字符串数组时,可以使用%w
lang = %w(ruby perl python scheme pike rebol)
p lang.sort{|a,b|a.length<=>b.length}

#使用%i创建符号数组
# lang = %w(ruby perl python scheme pike rebol)
# p lang=end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: