[ 'cat', 'dog', 'horse' ].each {|name| print name, " " }
5.times { print "*" }
3.upto(6) {|i| print i }
('a'..'e').each {|char| print char }
produces:
cat dog horse *****3456abcde
line.sub(/Perl/, 'Ruby') # replace first 'Perl' with 'Ruby'
line.gsub(/Python/, 'Ruby') # replace every 'Python' with 'Ruby'
You
can replace every occurrence of Perl and Python with Ruby using
line.gsub(/Perl|Python/, 'Ruby')
a = [ 1, 3, 5, 7, 9 ]
a[1] -> 9
a[2] -> 7
a[99] -> nil
a = [ 1, 3, 5, 7, 9 ]
a[1..3] -> [3, 5, 7]
a[1...3] -> [3, 5]#不包含最后一个。
a[3..3] -> [7]
a[3..1] -> [5, 7, 9]
3.times { print "X " }
1.upto(5) {|i| print i, " " }
99.downto(95) {|i| print i, " " }
50.step(80, 5) {|i| print i, " " }
produces:
X X X 1 2 3 4 5 99 98 97 96 95 50 55 60 65 70 75 80