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

Ruby构造元素:数据、表达式、和流程控制

2015-01-21 09:23 204 查看
常量

在Ruby中的表达形式是以大写字母开头的变量名。Pi = 3.141592 Pi = 500。如果尝试修改,将给出警告

字符串

puts "abc" * 5

abcabcabc

操作符可以应用于字符串中。如:puts "x" > "y",比较ASCII值

获得ASCII值

puts ?x

puts 120.chr

插写

表达式(甚至代码逻辑)直接嵌入到字符串中

x = 10

y = 20

puts "#{x} + #{y} = #{x + y}"

10 + 20 = 30

使用插写方式不用显示地把数字转换成字符串。

数组

x = [1, 2, 3, 4]

puts x[2]

x[2] = "Fish" * 3

x = []

x << "Word"

<<是把数据放到数组末尾的运算符。也可以调用push方法,具有相同的效果

puts x.pop

从数组末尾弹出数据

迭代

[1, "test", 2, 3, 4].each{|element| puts element.to_s + "x" }

each方法可以在数组的元素中进行迭代,还可以用collect方法,对数组进行实时转换

[1, 2, 3, 4].collect{ | element | element * 2}

[2, 4, 6, 8]

数组减法,从主数组中删除两个数组都有的元素

x = [1, 2, 3, 4, 5]

y = [1, 2, 3]

z = x - y

puts z.inspect

检查数组是否为空

x = []

puts "x is empty" if x.empty?

数组是否包含某个元素

x = [1, 2, 3]

puts x.include?("x")

puts x.include?(3)

访问数组第一个和最后一个元素

x = [1, 2, 3]

puts x.first

puts x.last

反转数组

x = [1, 2, 3]

puts x.reverse.inspect

散列表

dictionary = { 'cat' => 'feline animal', 'dog' => 'canine animal' }

puts dictionary['cat']

散列表迭代

x = { "a" =>, "b" => 2}

x.each { |key, value| puts "#{key} equals #{value}" }

检索键

puts x.keys.inspect

删除散列表元素

x.delete("a")

有条件删除

x.delete_if { |key, value| value < 25 }

流程控制

if 与 unless

unless 与 if 正好相反。

三元运算符

age = 10

type = age < 18 ? "child" : "aduit"

elsif 与 case

fruit = "orange"

case fruit

when "orange"

color = "orange"

when "apple"

color = "green"

when "banana"

color = "yellow"

else

color = "unknow"

end

while 与 until

x = 1

while x < 100

puts x

x = x * 2

end

x = 1

until x > 99

puts x

x = x * 2

end

代码块

代码块本质是匿名的、无名的方法或函数。

def each_vowel(&code_block)

%w{a e i o u}.each { |vowel| code_block.call(vowel) }

end

each_vowel { |vowel| puts vowel }

yield自动检测传递给它的代码块

def each_vowel

%w{a e i o u}.each { |vowel| yield vowel }

end

each_vowel { |vowel| puts vowel }

可以将代码块存储在变量中

print_parameter_to_screen = lambda { |x| puts x }

print_parameter_to_screen.call(100)

ruby中的大数字

其他语言常常有数字大小的限制,通常是32个二进制位。Ruby则不同,它没有这方面的限制。

实际上,它是用不同的类来处理的,Fixnum和Bignum,会自动处理。边界值是1 073 741 823
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: