1.交互式ruby:
1irb
2.
string.split(str)把字符串拆分成有三个元素的数组
string.split(str)的返回值是一个数组,参数str是一个字符串
例如: “foo bar ,baz”.split(“,”) #在逗号处拆分字符串
结果如下:
1
2
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
1
2
3
4
5
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]
最后
以上就是高大月饼最近收集整理的关于Ruby基础笔记string.split(str)把字符串拆分成有三个元素的数组再说一下,%w 用于创建元素为字符串的数组打乱数组数组的几个操作哈希的全部内容,更多相关Ruby基础笔记string.split(str)把字符串拆分成有三个元素的数组再说一下,%w内容请搜索靠谱客的其他文章。
发表评论 取消回复