Ruby syntax notes, ruby syntax
Accept user input
first_name = gets.chomp
Uppercase letters
first_name.capitalize!
Uppercase letters
first_name.upcase!
Lower letters
first_name.downcase!
Multi-row output
Print <EOF # multiline output EOF
Note
# I am a comment
Variable acquisition
#{first_name}
Variable
- Global variable $
- Class variable @@
- Method variable @
- Local variables are lowercase letters or _
If/else
if a < b puts '1'elsif b < a puts '2'end
Class
class Classname def functionname(params) puts params endendclass1 = Classname.newclass1.functionname('1')unlessunless false print 'ok'else print 'no'end
Contain characters
print 'puts'user_input = gets.chompuser_input.downcase!if user_input.include?"s" print 'has s'end
Replacement character
# s -> thuser_input.gsub!(/s/,"th")
Output variable values in strings
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 ages have the increment operators ++ and -- (which also add or subtract 1 from a value), but Ruby does not
For Loop
# If 1... 10 contains 1-9, if 1. 10 contains 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
Array
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 number Iterator
10.times { print 'ok'})
Looping with 'with'
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
Articles you may be interested in:
- Ruby learning notes (1) first-time Grammar
- Ruby basic syntax learning Summary
- Example of ruby declarative syntax
- A summary of some basic syntax knowledge points in Ruby
- Basic Ruby syntax
- Recommended syntax style in Ruby Programming
- Ruby Basics