2009年5月3日 星期日

define a array

x=[]
x << "Apple"
x << "orange"
x << "banana"
puts x.length
puts x[0]
puts x[1]
puts x[2]
puts x.pop
puts x.pop
puts x.length

iteration string

string1="this is a ruby"
string1.scan(/./) {|letter| puts letter}
string1.scan(/../) {|letter| puts letter}

string2="there are $1000 dollers here 10 days"
string2.scan(/\d+/) do |x|
puts x
end

string substitution

string1="the language name is ruby"
puts string1.sub('a','A')
puts string1.gsub('a','A')

interpolation string

x=10
y=20
puts "#{x}+#{y}=#{x+y}"

my_string="It\'s a #{"bad " *5} world"
puts my_string

character char and value

avalue=?a
puts avalue
puts avalue.chr

mutli line in ruby string

string1="<<"NEF
welcome to use ruby language
nice to meet you
NEF

puts string1

string2=%q{
welcome to use ruby language
nice to meet you
}

puts string2

string3=%q!
welcome to use ruby language
nice to meet you
!

puts string3

loop syntax

syntax 1:

4.times {
puts "welcome to use ruby language"
}

syntax 2:

1.upto(5){
puts "nice to meet you"
}

10.downto(5){
puts "nice to meet you"
}

0.step(50,5){
puts "welcome to use ruby language"
}

1.upto(5) do |number|
puts number
end