ruby 与 rails

《ruby 教程》初识对象

2017-04-27  本文已影响23人  饥人谷_若愚

数组

数组的简单使用

arr = [1, 3, 3.14, "饥人谷", true]
p arr[0]   # => 1
p arr[-1]  # => true
p arr.length  # => 5
p arr.size  # => 5
arr[8] = "若愚"
p arr   # => [1, 3, 3.14, "饥人谷", true, nil, nil, nil, "若愚"]

数组循环

arr = [1, 3, 5, 6]
arr.each do |value|
  p value + value
end

do 和 end 间的代码叫做块,也可用 {}代替do和end,一般多行用do ... end ,单行用 {}

arr.each { |value| p value + value }

散列

简单使用

school = {"name" => "jirengu", "age" => 3}
p school["name"]  # => "jirengu"
# p school.age   错误写法

散列由 key 和 value 构成,中间用=>连接

people = {:name => "ruoyu", :sex => "male"}
p people[:name]  # => "ruoyu"

key 可以是字符串可以是数字,也可以是符号,如 :name。对于key 为符号的散列,可以把:写到后面。上面的写法和下面是等价的。

friend = {name: "fangfang", sex: "male"}
p people[:name]  # => "fangfang"

散列的遍历

friend = {name: "fangfang", sex: "male"}
friend.each do |key, value|
  p "#{key} : #{value}"
end

正则表达式

puts /el/ =~ "hello"  # => 1
puts /abc/ =~ "hello" # => nil

使用 =~来进行匹配, 如果匹配上得到匹配的下标,如果匹配不上得到nil

words = ["小明", "小刚", "小花", "大鱼"]
select_word = []
words.each do |word|
  if(/小/=~ word)
     select_word << word   # 向数组添加元素
  end
end
p select_word  # =>  ["小明", "小刚", "小花"]
上一篇下一篇

猜你喜欢

热点阅读