#############################  Array And Hash  #######################
#array with three elements
a = [1, 'ca', 3.14]

#access the first element
puts(a[0])
#set the third element(nil means nothing)
a[2] = nil
#dump out the array
puts a

#the other way of creating arrays of words
b = %w{cat dog ca}
puts b[1]

#create hash
inst_section = {
 'cello' => 'string',
 'clarinet' => 'woodwind',
 'drum' => 'percussion',
 'oboe' => 'woodwind',
 'trumpet' => 'brass',
 'violin' => 'string'
}

puts inst_section['oboe']

#create empty hash
#zero is default value, you can specify another default value.
histogram = Hash.new(0)
puts histogram['key1']

########################################  Control Structures   ##########################################
count = 0
# if statements
if count > 10
 puts "Try again"
elsif count == 3
 puts "You lose"
else
 puts "Enter a number"
end

#while statements
while count >= 0 and count < 100
 puts count
 
 count = count + 1
end

#gets method returns the next line from the standard input stream or nil when end of file is reached.
while line = gets
 puts line.downcase
end

#statement modifiers
puts "Danger, Will Robinson" if radiation > 3000

square = 2
square = square * square while square < 1000
 
######################################  Regular Expressions  ##########################################
/Perl|Pathon/
/P(erl|athon)/
/ab+c/
/ab*c/

#a time such as 12:34:56
/\d\d:\d\d:\d\d/
#Perl, zero or more other chars, then Python
/Perl.*Python/
#Perl, a space, and Python
/Perl Python/
#Perl, zero or more spaces, and Python
/Perl *Python/
#Perl, one or more spaces, and Python
/Perl +Python/
#Perl, whitespace characters, then Python
/Perl\s+Python/
#Ruby, a space, and either Perl or Python
/Ruby (Perl|Python)/

#match operator
if line =~ /Perl|Python/
 puts "Scripting language mentioned: #{line}"
end

#replace first 'Perl' with 'Ruby'
line.sub(/Perl/, 'Ruby')
#replace every 'Python' with 'Ruby'
line.gsub(/Python/, 'Ruby')
#replace every occurrence of Perl and Python with Ruby
line.gsub(/Perl|Python/, 'Ruby')

posted on 2008-02-10 20:53  IT Person  阅读(291)  评论(0编辑  收藏  举报