jiyanliang 发表于 2013-1-27 05:37:16

ROR学习系列7-Ruby基础6-Ruby中的哈希表和范围的使用

我们知道Hash是一个键值对,我们在Ruby中,可以这样来定义:
money_I_am_owed = {“Dan” => “$1,000,000”, “Claire” => “$500,000”}
测试一下
puts money_I_am_owed[“Dan”]
结果为:$1,000,000

下面仔细看一下:
pizza = {“first_topping” => “pepperoni”, “second_topping” => “sausage”}
puts pizza[“first_topping”]
puts pizza
puts pizza.length
receipts = {“day_one” => 5.03, “day_two” => 15_003.00}
puts receipts[“day_one”]
puts receipts[“day_two”]
结果为:
pepperoni
first_toppingpepperonisecond_toppingsausage
2
5.03
15003.0
这个很简单就不用解释了。

下面我们来看一下Ruby中的范围使用:
看一下代码:
my_range = 1..4
puts my_range
1
2
3
4
看看下面的:
my_new_range = 1...4
puts my_new_range
1
2
3 #不包含4
这里应该能看懂了吧。
下面看看更高级的:
range = 1..5            #creates 1, 2, 3, 4, 5
puts range.to_a
range = 1...5         #excludes the 5
puts range.to_a
range = “a”..”e”      #creates “a”, “b”, “c”, “d”, “e”
puts range.to_a
puts range.min          #prints “a”
puts range.max          #prints “e”
range = “alpha”..”alphe”
puts range.to_a
看一下结果:
1
2
3
4
5
1
2
3
4
a
b
c
d
e
a
e
alpha
alphb
alphc
alphd
alphe
页: [1]
查看完整版本: ROR学习系列7-Ruby基础6-Ruby中的哈希表和范围的使用