代码片段
# case_when_matcher_classes.rb
class Zigor
def self.===(string)
string.downcase == "zigor"
end
end
name = "Zigor"
case name
when Zigor
puts "Nice to meet you Zigor!!!"
else
puts "Who are you?"
end
10.downto 1 do |num|
p num
end
17.upto 23 do |i|
print "#{i}, "
end
1.step 10 do |i|
print "#{i}, "
end
# 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
10.step 1 do |i|
print "#{i}, "
end
#10, 9, 8, 7, 6, 5, 4, 3, 2, 1,
10.step 1, -2 do |i|
print "#{i}, "
end
# 10, 8, 6, 4, 2,
2.step 10, 2 do |i|
print "#{i}, "
end
# 2, 4, 6, 8, 10,
redo:
5.times do |num|
puts "num = #{num}"
puts "Do you want to redo? (y/n): "
option = gets.chop
redo if option == 'y'
end
array
dig
>> array = [1, 5, [7, 9, 11, ["Treasure"], "Sigma"]]
=> [1, 5, [7, 9, 11, ["Treasure"], "Sigma"]]
>> array.dig(2, 3, 0)
=> "Treasure"
=> array[2][3][0]
>> "Treasure"
array
>> volleyball=["Ashok", "Chavan", "Karthik", "Jesus", "Budha"]
=> ["Ashok", "Chavan", "Karthik", "Jesus", "Budha"]
>> cricket=["Budha", "Karthik", "Ragu", "Ram"]
=> ["Budha", "Karthik", "Ragu", "Ram"]
>> volleyball & cricket
=> ["Karthik", "Budha"]
>> volleyball | cricket
=> ["Ashok", "Chavan", "Karthik", "Jesus", "Budha", "Ragu", "Ram"]
>> volleyball + cricket
=> ["Ashok", "Chavan", "Karthik", "Jesus", "Budha", "Budha", "Karthik", "Ragu",
"Ram"]
>> volleyball - cricket
=> ["Ashok", "Chavan", "Jesus"]
作用域
$x = 5
def print_x
$x = 3
puts $x
end
print_x
puts $x
# 3
# 3
对象
class Square
attr_accessor :side_length
def initialize side_length = 0
@side_length = side_length
end
def area
@side_length * @side_length
end
def perimeter
4 * @side_length
end
end
s1 = Square.new 4
s2 = Square.new
s2.side_length = 5
puts "Area of s1 is #{s1.area} squnits"
puts "Peimeter of s2 is #{s2.perimeter} units"
Output
Area of s1 is 16 squnits
Perimeter of s2 is 20 units
chmod a+x shebang.rb