|
The caret operator ^ and the $ operator are used for matching at the start of a string,respectively at the end of a string.
Example:
matching = /[a-e]$/
The script would look for any of the letters between a and e inclusive at the end of a string.
Searching for a letter inside a string:
[A-Z] all letters uppercase
[a-z] all letters lowercase
[0-9] all digits
You can also restrict the range, if you want to look only for letters between a and e you would write it as [a-e].
Combining these with the caret operator:
[^A-Z] all other characters except uppercase letters
[^a-z] all other characters except lowercase letters
[^A-Za-z] no letters, no matter if uppercase or lowercase
Using the "match" method of the Regexp class
The method matches a regular expression against a string.If success, it returns an instance of class MatchData.The MatchData object gives you access to information about the match made.The method will return 'nil if nothing has been matched.
re = /(\d+):(\d+)/ # match a time hh:mm
md = re.match("Time: 12:34am")
md.type # -> MatchData
md[0] # == $& # -> "12:34"
md[1] # == $1 # -> "12"
md[2] # == $2 # -> "34"
md.pre_match # == $` # -> "Time: "
md.post_match # == $' # -> "am"
Wonderful example quote from [1]
The match method allows you to do most of the things the $ sign would do,and then some.
[edit] Ruby Blocks
A block is a nameless function.As the creator of Ruby,Yukihiro Matsumoto says, "in Ruby, any method can be called with a block as an implicit argument. Inside the method, you can call the block using the yield keyword with a value."
He also says that the main reason he designed blocks for Ruby is for "loop abstraction. The most basic usage of blocks is to let you define your own way for iterating over the items."
These comments are excerpted from an interview he gave some while ago that you can ready in full here
Since it's early stages, the use of blocks in Ruby has evolved from being strictly used for iterations to a lot more other purposes.We will later discuss closures also that have a lot of similarities to blocks.
A block is either enclosed between {} or between do...end like this:
{ puts "I am a block!" }
do
puts "I am a block!" /*for multi-line blocks*/
end
How do you use a block?
With a yield statement like this:
def shout()
yield
end
shout { puts "I am a block!" }
This code defines a method called "shout" and then it calls the method.Methods will be explained in a later chapter.
|