Ruby基础笔记

来源:互联网 发布:wlanapi.dll修复软件 编辑:程序博客网 时间:2024/06/07 19:37

1.交互式ruby:

irb

2.

把字符串拆分成有三个元素的数组

例如: “foo bar ,baz”.split(“,”) #在逗号处拆分字符串
结果如下:

2.4.0 :004 > "foo bar ,baz".split(",") => ["foo bar ", "baz"]

其中:str.split等于str.split(” “)

s.downcase 把大写转成小写

%w[a b c]

再说一下,%w 用于创建元素为字符串的数组

=> [“a”, “b”, “c”]

(‘a’..’z’).to_a.shuffle

打乱数组

数组的几个操作

a.length 长度
a.empty?
a.include?(42) 判断a是否包含42
a.sort 返回一个数组,但是不改变a的值
a.sort! 返回一个数组,并改变a的值
a.reverse #反转
a.shuffle 乱序
a.first a.second a.last
a.push(6) 把6加到数组末尾
a<<7 把7加到数组末尾

a << “foo” << “bar” 串联操作,结果如下
[42, 8, 17, 6, 7, “foo”, “bar”]

a.join 连接成字符串
a.join(‘, ‘) 连接成字符串,中间用’, ‘隔开
值域类转数组:
a=1..9
b=a.to_a 或者 b.(1..9).to_a
创建字符串数组:
a = %w[foo bar baz quux]
得到
[“foo”, “bar”, “baz”, “quux”]

哈希

user={} <=> user=Hash.new
user=Hash.new(0) 不存在的键值返回0而不是new
操作一:user{“first_name”}=”hou”
操作二:user={“name”=>”hello”,”val”=>”hch”}
操作三:user={:name=>”hello”}
操作四user={name:”hello”}

删除数组重复元素 array.uniq

2.4.0 :013 > arry=array.map{|x| x.to_i} => [1, 2, 3, 4, 5, 6, 1] 2.4.0 :014 > arry.uniq => [1, 2, 3, 4, 5, 6]