Ruby语法笔记
接受用户输入
first_name=gets.chomp
首字母大写
first_name.capitalize!
字母变大写
first_name.upcase!
字母变小写
first_name.downcase!
多行输出
print<<EOF #多行输出 EOF
注释
#我是注释
变量获取
#{first_name}
变量
- 全局变量$
- 类变量@@
- 方法变量@
- 局部变量小写字母或_
if/else
ifa<b puts'1' elsifb<a puts'2' end
类
classClassname deffunctionname(params) putsparams end end class1=Classname.new class1.functionname('1') unless unlessfalse print'ok' else print'no' end
是否包含字符
print'puts' user_input=gets.chomp user_input.downcase! ifuser_input.include?"s" print'hass' end
替换字符
#s->th user_input.gsub!(/s/,"th")
在字符串中输出变量值
puts'okok#{user_input}'
while
counter=1 whilecounter<11 putscounter counter=counter+1 end
Until
counter=1 untilcounter>10 printcounter counter=counter+1 end
+=、-=、*=、/=
Somelanguageshavetheincrementoperators++and--(whichalsoaddorsubtract1fromavalue),butRubydoesnot
for循环
#如果1...10包含1-9,如果1..10包含1-10
fornumin1...10 putsnum end
LoopMethod
AniteratorisjustaRubymethodthatrepeatedlyinvokesablockofcode.
i=20 loopdo i-=1 print"#{i}" breakifi<=0 end
Next
i=20 loopdo i-=1 nextifi%2!=0 print"#{i}" breakifi<=0 end
数组
my_array=[1,2,3,4,5]
The.eachIterator迭代器
numbers=[1,2,3,4,5] #onewaytoloop numbers.each{|item|putsitem} #anotherwaytoloop numbers.eachdo|item| putsitem end
The.timesIterator次数迭代器
10.times{print'ok'})
Loopingwith'While'
num=1 whilenum<=50do printnum num+=1 end
Loopingwith'Until'
num=1 untilnum>50do printnum num+=1 end
LooptheLoopwithLoop
num=0 loopdo num+=1 print"Ruby!" breakifnum==30 end
The.splitMethod,
text.split(",") puts"Texttosearchthrough:" text=gets.chomp puts"Wordtoredact" redact=gets.chomp words=text.split("") words.eachdo|word| printword end