Comments
In Ruby, any text on a single line that follows a # is a comment, and is ignored by the Ruby interpreter at run time.# comment
Function Calls
Parentheses can sometimes be omitted. If you're not sure whether they're required, put them in. To be safe, put them in whenever the call is at all complicated. Even one as simple as this.puts "hello" puts("hello") assert_equal(5, number)
Variables
Ordinary (local) variables are created through assignment:number = 5
this_is_my_variable = 5
number + this_is_my_variable # returns 10
Strings, Objects and Methods
Strings are sequences of text in quotation marks. You can use single or double quotes.name = 'simon' name = "simon"
A method call looks like this:
"simon".upcase # returns "SIMON"
Like functions, methods can have arguments.
"bookkeeper".include?('book') # returns true
You can also concatenate strings using the + operator.
"dog" + "house" # returns "doghouse"
Conditionals (if)
if number == 5 puts "Success" # "Success" is a string. Strings can be surrounded with single or double quotes. else puts "FAILURE" end
Function Definitions
def assert_equal(expected, actual) if expected != actual puts "FAILURE!" end end
def five # note that no parentheses are required 5 end box = five # box's value is 5
The value of the last statement is always the value returned by the function. Some people like to include a return statement to make this clear, but it doesn't change how the function works. This does the same thing:
def five return 5 end
def make_positive(number) if number < 0 -number else number end end variable = make_positive(-5) # variable's value is 5 variable = make_positive(five) # variable's value is 5
Libraries
Libraries contain functions or methods that can be used in many Ruby programs. Suppose we store the make_positive function defined above in a file called mathplus.rb.To use it in another script, we must require it:
require 'mathplus'
If your library is in a location that Ruby doesn't know about, you will need to change the loadpath:
$LOAD_PATH << 'c:/my_lib/'
Arrays
This is an array with nothing in it:[]
[1, 2]
[1, 'hello!', 220]
array = [1, 'hello', 220] array[0] # value is 1
array[2] # value is 220
array.last # value is 220
array[0]= 'boo!' # value printed is 'boo!' # array is now ['boo', 'hello', 220]
array.length # value is 3
array.push('fred') # array is now ['boo', 'hello', 220, 'fred']
Iteration
When you do something multiple times, it is called iteration. There are many ways to do this. The following will print hello five times:5.times do puts 'hello' end
for x in 1..10 do puts x end
(1..10).each do |x| puts x end
(1..10).each { |x| puts x }
This prints each value of an array:
["a", "b", "c"].each { |x| puts x }
["hi", "there"].collect { |word| word.capitalize } # The result is ["Hi", "There"].
Regular Expressions
Regular expressions are a useful feature common to many languages. They allow you to match patterns in strings.Regular expressions are characters surrounded by // or %r{}. A regular expression is compared to a string like this:
regexp =~ string
/a/ =~ 'a string' /a/ =~ 'string me along'
/as/ =~ 'a string with astounding length'
/^as/ =~ 'alas, no match'
/no$/ =~ 'no match, alas'
/^.s/ =~ "As if I didn't know better!"
Truth and Falsehood
If you try the examples above, you'll see that the ones that match print a number. That's the position of the first character in the match. The first expression (/a/ =~ 'a string') returns 0. (Ruby, like most programming languages, starts counting with 0.) The second returns 10.What happens if there's no match? Type this:
/^as/ =~ 'alas, no match'
if /^as/ =~ some_string puts 'the string begins with "as".' end
Blocks
A block is like a function without a name. It contains a set of parameters and one or more lines of code. Blocks are used a lot in Ruby. Iterators like each use blocks.Here's how to search an array for an element:
gems = ['emerald', 'pearl', 'ruby'] gems.detect { |gem| /^r/ =~ gem } # returns "ruby"
When blocks are longer than one line, they are usually written using do and end. This is another way of writing the same code:
gems.detect do |gem| /^r/ =~ gem end
Dictionaries
A dictionary lets you say "Give me the value corresponding to key." Dictionaries are also called hashes or associative arrays.Here's how you create a dictionary:
dict = {}
dict['bret'] = 'texas' # looks a lot like an array, except that the key doesn't have to be a number.
dict['bret'] # value is 'texas'.
dict.length # value is 1
dict.values # value is the Array ['texas'].
dict.keys # value is the Array ['bret'].
Expression Substitution
Expression substitution evaluates an expression within a string:You can do this
name = "Aidy" puts "My name is: #{name}" => My name is: Aidy
puts "The sum of four times four is: #{4*4}" => The sum of four times four is: 16
No comments:
Post a Comment