<Ruby> Basics
1.
puts "Hello"
This write "Hello" to the screen with a new line tailed to.
print "Hello"
Just like puts, but without new line.
2.
"You know nothing".length
This output the string length.
"Jon Snow".reverse
"wonS noJ"
"OVERWATCH".downcase #---> "overwatch" "overwatch".upcase #---> "OVERWATCH"
Let's play Overwatch...
3.
# I'm a single line comment! =begin Well, I am a multiple line COMMENT! =end
4.
variable_name = gets.chomp
gets is the Ruby method that gets input from the user. When getting input, Ruby automatically adds a blank line (or newline) after each bit of input; chomp removes that extra line. (Your program will work fine without chomp, but you'll get extra blank lines everywhere.)
gets is the Ruby method that getsinput from the user. When getting input, Ruby automatically adds a blank line (or newline) after each bit of input; chomp removes that extra line. (Your program will work fine withoutchomp, but you'll get extra blank lines everywhere.)
5.
name = "Jack" name = name.capitalize name.capitalize!
There are two ways to assign method return value to a variable.
6.
if hungry puts "Time to eat!" else puts "I'm writing Ruby programs!" end unless hungry puts "I'm writing Ruby programs!" else puts "Time to eat!" end
There two ways of flow control in Ruby, if & unless. unless is the reversed if.
7.
# two dots range for num in 1..15 puts num end # three dots range for num in 1...15 puts num end
The first range includes the highest number, 15, while the second one does not.
8.
i = 20 loop do i -= 1 print "#{i}" break if i <= 0 end
Apart from for, while, there is also a loop do in Ruby.
9.
i = 20 loop do i -= 1 next if i % 2 == 1 ### print "#{i}" break if i <= 0 end
Next, just like continue in many other languages, skips current loop when the condition is fulfilled.
10.
my_array = [1, 2, 3, 4, 5]
Like Python, this is how Ruby defines a array.
my_array.each do |x| x += 10 print "#{x}" end
To iterate array, the simplest way is using the .each iterator. x is the placeholder for each element of the object you're using .each on.
my_array.each do { |x| print "#{x}" }
This is a simplified usage of .each do.
11. the .times iterator
10.times { print "Chunky bacon!" }
The .times method is like a super compact for loop: it can perform a task on each item in an object a specified number of times.

浙公网安备 33010602011771号