ruby language
ruby language
2022-07-06
是真的方便
-
循环?
1 2 3 4 5
5.times do print 'hello world!' end
-
数学计算?
2 + 3 -
打印?put something on the screen
puts xxx -
重复多个字符串?
"ruby" * 5 -
类型抓换?
to_s转换为字符串to_a转换为数组to_i转换为整数 -
定义数组?
arr = [1,2,3] -
数组长度?最大值?最小值?反转?排序?
[12, 47, 35].length[12, 47, 35].max[12, 47, 35].min[12, 47, 35].reverse[12, 47, 35].sort!… -
数组排序是否修改原数组?
arr = [1,2,3]arr.sort!加!标记在原数组上排序 -
读取、存放数组
puts arr[1]arr[1] = 4 -
一些字符串操作方法
name = "ruby is nice"name.gsub("nice", "so nice")name.reversename.lines -
方法链式调用?
str = "Hello world!\n I am Ruby!"str.lines.reverse.join -
hash
books = {}books["The deep end"] = :abysmalbooks["Living colors"] = :mediocreputs booksputs books.lengthputs books["The deep end"]:取valuebooks.keysbooks.values -
:的含义?单词前加
:, 会让这个单词在内存里只存一份。这样节省内存。但是加上
:就不再是简单的字符串了。 -
分支?
1 2 3 4 5
if 1 < 2 puts "It is true: 1 is less than 2" end puts "It is true: 1 is less than 2" if 1 < 0
- What does the question mark at the end of a method name mean?
-
It is a code style convention; it indicates that a method returns a boolean value (true or false) or an object to indicate a true value (or “truthy” value).
The question mark is a valid character at the end of a method name.
https://docs.ruby-lang.org/en/2.0.0/syntax/methods_rdoc.html#label-Method+Names
-
-
打印替换
#{}里面放变量,比如#{name} -
面向对象:定义类
1 2 3 4 5 6 7 8
class Blurb attr_accessor :content, :time, :mood def initialize(mood, content="") @time = Time.now @content = content[0..39] @mood = mood end end
这里的
@,和使用.调用意思一样。在类里面调用对象的变量用@,类外用.