我是靠谱客的博主 怕黑板栗,这篇文章主要介绍Ruby语法笔记,现在分享给大家,希望可以做个参考。

接受用户输入

复制代码
1
first_name = gets.chomp

首字母大写

复制代码
1
first_name.capitalize!

字母变大写

复制代码
1
first_name.upcase!

字母变小写

复制代码
1
first_name.downcase!

多行输出

复制代码
1
2
3
print <<EOF # 多行输出 EOF

注释

复制代码
1
# 我是注释

变量获取

复制代码
1
#{first_name}

变量

  1. 全局变量 $
  2. 类变量 @@
  3. 方法变量 @
  4. 局部变量 小写字母或_

if/else

复制代码
1
2
3
4
5
if a < b puts '1' elsif b < a puts '2' end


复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Classname def functionname(params) puts params end end class1 = Classname.new class1.functionname('1') unless unless false print 'ok' else print 'no' end

是否包含字符

复制代码
1
2
3
4
5
6
7
8
9
print 'puts' user_input = gets.chomp user_input.downcase! if user_input.include?"s" print 'has s' end

替换字符

复制代码
1
2
# s -> th user_input.gsub!(/s/,"th")

在字符串中输出变量值

复制代码
1
puts 'okok #{user_input}'

while

复制代码
1
2
3
4
5
6
counter = 1 while counter < 11 puts counter counter = counter + 1 end

Until

复制代码
1
2
3
4
5
counter = 1 until counter > 10 print counter counter = counter + 1 end

+= 、 -= 、 *=、 /=
Some languages have the increment operators ++ and -- (which also add or subtract 1 from a value), but Ruby does not
for循环
# 如果 1...10 包含1-9,如果 1..10 包含1-10

复制代码
1
2
3
for num in 1...10 puts num end

Loop Method
An iterator is just a Ruby method that repeatedly invokes a block of code.

复制代码
1
2
3
4
5
6
i = 20 loop do i -= 1 print "#{ i }" break if i <= 0 end

Next

复制代码
1
2
3
4
5
6
7
i = 20 loop do i -= 1 next if i%2 != 0 print "#{i}" break if i <= 0 end

数组

复制代码
1
my_array = [1,2,3,4,5]

The .each Iterator迭代器

复制代码
1
2
3
4
5
6
7
8
9
numbers = [1, 2, 3, 4, 5] # one way to loop numbers.each { |item| puts item } # another way to loop numbers.each do |item| puts item end

The .times Iterator 次数迭代器

复制代码
1
10.times { print 'ok'})

Looping with 'While'

复制代码
1
2
3
4
5
6
num = 1 while num <= 50 do print num num += 1 end

Looping with 'Until'

复制代码
1
2
3
4
5
num = 1 until num > 50 do print num num += 1 end

Loop the Loop with Loop

复制代码
1
2
3
4
5
6
7
num = 0 loop do num += 1 print "Ruby!" break if num == 30 end

The .split Method,

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
text.split(",") puts "Text to search through: " text = gets.chomp puts "Word to redact" redact = gets.chomp words = text.split(" ") words.each do |word| print word end

最后

以上就是怕黑板栗最近收集整理的关于Ruby语法笔记的全部内容,更多相关Ruby语法笔记内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(194)

评论列表共有 0 条评论

立即
投稿
返回
顶部