Ruby文法筆記_ruby專題

來源:互聯網
上載者:User

接受使用者輸入

first_name = gets.chomp

首字母大寫

first_name.capitalize!

字母變大寫

first_name.upcase!

字母變小寫

first_name.downcase!

多行輸出

print <<EOF  # 多行輸出EOF

注釋

# 我是注釋

變數擷取

#{first_name}

變數

  1. 全域變數 $
  2. 類變數 @@
  3. 方法變數 @
  4. 局部變數 小寫字母或_

if/else

if a < b  puts '1'elsif b < a  puts '2'end    


class Classname  def functionname(params)    puts params  endendclass1 = Classname.newclass1.functionname('1')unlessunless false  print 'ok'else  print 'no'end    

是否包含字元

print 'puts'user_input = gets.chompuser_input.downcase!if user_input.include?"s"  print 'has s'end

替換字元

# s -> thuser_input.gsub!(/s/,"th")

在字串中輸出變數值

puts 'okok #{user_input}'

while

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

Until

counter = 1until counter > 10  print counter  counter = counter + 1end  

+= 、 -= 、 *=、 /=
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 numend  

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

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

Next

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

數組

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

The .each Iterator迭代器

numbers = [1, 2, 3, 4, 5]# one way to loopnumbers.each { |item| puts item }# another way to loopnumbers.each do |item| puts itemend

The .times Iterator 次數迭代器

10.times { print 'ok'})

Looping with 'While'

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

Looping with 'Until'

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

Loop the Loop with Loop

num = 0loop do  num += 1  print "Ruby!"  break if num == 30end  

The .split Method,

text.split(",")puts "Text to search through: "text = gets.chompputs "Word to redact"redact = gets.chompwords = text.split(" ")words.each do |word|  print wordend

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.