10 分钟的入门

函数后面的!和?

1.  问号
    方法名后面加问号是 Ruby 的编码风格规范,用来表示该方法会返回一个 boolean 类型的值,但是并不会强制该方法一定要返回 boolean 值。
2.  感叹号
    方法名后面加感叹号是 Ruby 的编码风格规范,用来表示该方法会去修改对象本身,Ruby 会把带有感叹号的方法称为危险的方法,因为程序中可能有其他地方会引用这个对象。但是并不会强制该方法一定要修改对象本身。

反转

> "str".reverse
  => "rts"

转化

str = 40
str.to_s!
str.to_i

数组

> []

打印 赋值 替换

//  赋值
poem = "My toast has flown from my hand
And my toast has gone to the moon.
But when I saw it on television,
Planting our flag on Halley's comet,
More still did I want to eat it."
// 替换
poem['toas­t']='honey­dew'
=> "honeydew"
Success!
// 打印
> print poem
=> "My honeydew has flown from my hand
And my toast has gone to the moon.
But when I saw it on television,
Planting our flag on Halley's comet,
More still did I want to eat it."

拆分,转化,排序

> poem.lines­.to_a.reve­rse
=> ["More still did I want to eat it.
", "Planting our flag on Halley's comet,
", "But when I saw it on television,
", "And my toast has gone to the moon.
", "My honeydew has flown from my hand
"]
Success!

ruby中的join,split,send,map,each,collect,inject方法总结

字符串转数组,数组转字符串

> print poem.lines­.to_a.reve­rse.join

哈希

> books = {}
=> {}
Success!
> books["Gra­vity's Rainb­ow"]
=> :splendid
Success!

> books.keys­
=> ["Gravity's Rainbow"]
// 初始化 
> ratings = Hash.­new(0)
=> {}
Success!
 
> books.valu­es.each{ |rate­| ratin­gs[rate] +=1 }
=> [:splendid, "sssss"]

> ratings
=> {:splendid=>1, "sssss"=>1}
> 

ruby 写法注意

  • ruby 方法调用的时候,当使用圆括号包裹参数的时候,切记左括号要紧贴方法名不能留白
# 错误的写法
p (sum 2,3)   # 语意分歧 p (sum (2),3)  or p (sum(2,3)) ?
# 正确写法
p sum(2,3) 
p (sum 2,2) # p方法后的空格指明后面一个参数是 方法sum的结果

你可能感兴趣的:(10 分钟的入门)