#自己动手写一个Hash.grep,在key或value中搜索匹配正则表达式的名/值对,输出出来。
animals=Hash['cat','111','dog','222','fish','fff']
#key match /[ia]/
results=animals.keys.grep(/[ia]/)
results.each{|key| print key,'=>',animals[key],"\n"}
#value match
keys=animals.keys
keys.each{|key|
if /([0-9]+)/ =~ animals[key] then
print key,'=>',animals[key],"\n"
end
}
#尝试用最少的ruby语句实现快速排序
list=[9,2,3,7,0,1,4]
def quicksort(list)
return list if list.size <= 1
pivot = list.sample
left, right = list.partition { |e| e < pivot }
quicksort(left) + quicksort(right)
end
print quicksort(list),"\n"
Ruby之散列与快排小程序
最新推荐文章于 2021-01-29 22:20:21 发布