Ruby语法笔记(ruby ruby)奔走相告

随心笔谈3年前发布 admin
220 0 0

文章摘要

这篇文章介绍了Ruby语言的基础语法和一些常见操作。内容主要涵盖以下几个部分: 1. **变量操作**:包括变量的获取、字符串的标题转换、替换字符、在字符串中输出变量值等操作。 2. **字符串处理**:展示了如何使用`include?`方法检查字符是否存在,以及使用`gsub!`方法替换字符。 3. **循环结构**:介绍了`for`循环、基于`until`的循环以及自增操作(`+=`, `-=`, `*=`, `/=`)。 4. **类和方法**:解释了类的定义、调用方法以及使用条件语句(`if/else`)。 5. **数组操作**:探讨了数组的迭代器及其在循环中的应用。 6. **输入输出**:展示了如何处理多行输入和注释。 文章通过具体的示例详细说明了Ruby语言的语法和用法,内容简洁明了,适合初学者学习。



接受用户输入

first_name=gets.chomp

首字母大写

first_name.capitalize!

字母变大写

first_name.upcase!

字母变小写

first_name.downcase!

多行输出

print <<EOF
# 多行输出
EOF

注释

# 我是注释

变量获取

#{first_name}

变量

全局变量 $
类变量 @@
方法变量 @
局部变量 小写字母或_

if/else

if a < b
puts ‘1’
elsif b < a
puts ‘2’
end

class Classname
def functionname(params)
puts params
end
end

class1=Classname.new
class1.functionname(‘1’)
unless
unless false
print ‘ok’
else
print ‘no’
end

是否包含字符

print ‘puts’

user_input=gets.chomp

user_input.downcase!

if user_input.include?”s”
print ‘has s’
end

替换字符

# s -> th
user_input.gsub!(/s/,”th”)

在字符串中输出变量值

puts ‘okok #{user_input}’

while

counter=1

while counter < 11
puts counter
counter=counter + 1
end

Until

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

for num in 1…10
puts num
end

Loop Method

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

i=20
loop do
i -=1
print “#{ i }”
break if i <=0
end

Next

i=20
loop do
i -=1
next if i%2 !=0
print “#{i}”
break if i <=0
end

数组

my_array=[1,2,3,4,5]

The .each Iterator迭代器

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 次数迭代器

10.times { print ‘ok’})

Looping with ‘While’

num=1

while num <=50 do
print num
num +=1
end

Looping with ‘Until’

num=1
until num > 50 do
print num
num +=1
end

Loop the Loop with Loop

num=0

loop do
num +=1
print “Ruby!”
break if num==30
end

The .split Method,

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编程中的语法使用风格推荐Ruby基础语法初探Ruby中一些基本语法知识点的罗列汇总ruby声明式语法的实现例子Ruby的基本语法学习总结ruby 学习笔记(1) 初识语法Ruby的语法和语言特性总结

© 版权声明

相关文章