这个部分主要讲遍历和循环

while的用法

#while的两种语法
i = 0
while i<10 do
  puts "hello world"
  i += 1
end

while i<10  #省略10
  puts "hello world"
  i += 1
end

#备注,ruby中没有i++这种用法,只有i+=的这种用法,i+=1等于 i=i+1

each的用法

arr = ["one", "two", "three"]
#each使用block的两种用法
arr.each do |i|
  p i
end

arr.each{ |i| p i}

for的用法,rails中不常用这个做循环

#代码
for i in 1..3; p i ;end #1,2,3

#备注:1..3,包括3, 1...3,不包括3

nested loop

hash = {
  "jayzen": {
    "sex": "male",
    "age": "29"
  },
  "jay": {
    "sex": "female",
    "age": "28"
  }
}

hash.each do |name, attributes|
  p name
  attributes.each do |set, age|
    p set
    p age
  end
end

select的用法

#选择出偶数部分
(1..10).to_a.select(&:even?) #使用&的形式
(1..10).to_a.select do |i|; i.even?; end #使用do end形式
(1..10).to_a.select { |i|; i.even? } #使用{}形式

#选择字母为元音的字母(vowel)
%w(a b c d e f g h i j k).select do |i|; i =~ /[aeiou]/ ; end


#用grep(enumerable的方法)代替select和map
arr = ["hey.rb", "there.rb", "index.html"]
arr.select{|x| x=~ /\.rb/}.map{|x| x[0..-4]} #["hey", "there"]
arr.grep(/(.*)\.rb/){$1} #["hey", "there"]

map的用法

#map和each的区别,each遍历原有的值,返回原来的数组,map遍历原来值,返回改变后的值,但是不改变原有值
%w(1 2 3 4).each {|i| i.to_i } #["1", "2", "3", "4"]
%w(1 2 3 4).map {|i| i.to_i } #[1, 2, 3, 4] ,同%w(1 2 3 4).map(&:to_i)

#map的例子
("a".."z").to_a.map{|i| i*2} #注意("a".."z").to_a
[1,2,3,4,5].map{|x| [x, x.to_i]} #生成hash的例子
Hash[%w(a bc def).map{|i|[i, i.length]}] #计算单词的长度,{"a"=>1, "bc"=>2, "def"=>3}
Hash["name": "jayzen", "age": "29"].map{|a, b| "#{a}=#{b}"}.join("&") #转换成url搜索的样式, "name=jayzen&age=29"

inject&reduce

#用法参考之前积累

results matching ""

    No results matching ""