292人参与 • 2024-05-19 • 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
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论