MapleCity Blog

MapleCity Blog header image 2

Ruby Notes

January 27th, 2008 · 1 Comment

** In order to become proficient with the rails framework you really need to know quite a bit about ruby as a programming language.

Ruby References:

  • web page: http://corelib.rubyonrails.org //core library for the ruby programming language
  • book: “Programming Ruby” by Dave Thomas (aka: The Pick Axe Book)

Logs

  • if you programming and something has gone wrong often the error logs will give a clue as to what is going wrong.
  • there is a folder called “log” depending what mode your working in you’ll need to refer to that log file. “Production”, “Development”, and “Test”
  • there is a log file specifically for server errors as well called “Server”
  • one note about these log files is that you should keep your eye on the file size of the development log because it will become difficult to read as ruby continually will append new messages, and you should keep your eye on the production log because this will give you clues as to what is happening on the users end.
  • as a rails developer you can also write to the log files using the logger object which is built into the framework: logger.warn(’<string to write>’)
    • there are four types of logging that you can put into your log files:
      • warning()
      • info()
      • error()
      • fatal()

Inspecting

  • you can use the .inspect method to check what is being sent back to your page with both parameters and instance variables:
    • @<instance_variable>.inspect
    • params.inspect
  • in addition to inspecting what is being sent back you can also check the type of a variable by using the .type method:
    • @<instance_variable>.type

Comments

  • a simple but effective way to write code is to comment. No programmer does it enough.
  • to create a comment in ruby you simply proceed the line with a # sign, this applies to files that end in .rb for files that end in .rhtml things are a little different.
  • to create a comment in an .rhtml file you need to use the brackets style <% # … %> in-line or multi-line would be <%# … %>

Ruby Variables

  • you can declare a variable without having to define it’s type. To declare a variable: <variable_name> = <value>
  • There are different types of variables in ruby:
    • local_variable = is usually a variable defined in a normal way and is what you’ll use if you want a normal local variable. Defined such as name = value
    • $global_variable = available throughout the application
    • @instance_variables = are usually preceded with an @ symbol such as @name = value
    • @@class_variable
    • CONSTANT = a value that doesn’t change it can be set but cannot be overridden later on in the application
    • :symbol = not a variable or a constant but are used a lot in rails. Is used when we want to talk about the name of something not the value it contains
    • ClassName = the uppercase is important in these naming schemes, especially for class names.
  • local_variables that are set in the controller are not available in the view. The variables need to be instance variables in order to be available in the view.

Strings

  • you can use either double quotes or single quotes around strings.
  • escape character for strings is \
  • if you want to add an expression directly into a string you can use the double quotes like this: “<string>#{<expression>}<string>”
  • the string class is one of the many classes in ruby.
  • a string is composed of a series of characters.. a letter, a paragraph, a word, a sentence…etc…
  • method that is common is the concatenation method as seen in two forms (+) or .concat()
  • multiply is another common string method (*) does as it name implies and multiples the string as many times as specified.
  • (.)dot notation (more often this is the form a method will take on in the string class)
  • some other methods of the string class that are common are:
    • .capitalize
    • .upcase
    • .downcase
    • .swapcase
    • .reverse
  • you can also daisy chain methods together <string>.downcase.swapcase.reverse
  • you can strip white space by using the .strip method
  • you can get a strings length by using the .length method
  • you can insert characters into a string using the .insert() method

Numbers

  • numbers come in two types in ruby: integer and floating point numbers
  • ruby has all the common operators you’d expect such as: +, -, *, etc…
  • numbers and strings are certainly not the same thing so a ‘1′ and 1 are not the same thing.
  • there is a method that will convert numbers to string called .to_s
  • the default number type in ruby is integer so if you want to work with floating point numbers you need to be specific
  • there is a method that will convert numbers to floating point numbers called .to_f
  • some other methods of the floating point type are:
    • .round
    • .ceil //always rounds up
    • .floor //always rounds down
  • there is a shortcut way to increment and decrement a variable by using the shortcut syntax of: += or -=
  • the keyword: nil means essentially “nothing”… like an empty variable.

Arrays

  • an array is “an ordered integer indexed collection”
  • ruby uses array’s much more often than most other languages
  • array’s are very useful when working with lots of data and databases
  • to define an array you would use the following syntax: <array_name> = [<value1>, <value2>, <etc...>]
  • to pull values out of the array you simply reference the index of the array you want: <array_name>[<index>]
  • to remove an element from an array simply assign nil to the index of the array.
  • to remove an entire array you simply re-initialize it back to an empty array: <array_name> = []
  • arrays are numbered starting at 0
  • some of the methods of the array class include the following:
    • .join()
    • .first //get the first item of an array
    • .last //get the last item of an array
    • << = <value_to_append> //append a value onto the end of the array
    • .delete() //delete the given value from the array
    • .length //returns the number of elements in an array
    • .reverse //reverse the elements in an array but this is a non-destructive method
    • ***adding ! at the end of a non-destructive method makes it destructive and it becomes a change in place
    • .sort //sort the elements in an array, this is also a non-destructive method
    • .uniq //remove unique values (duplicates) from an array
    • .split() //takes a string and creates an array from it based on some separator

Hashes

  • a has is a special kind of array
  • the indexes of a hash received labels instead of numbers
  • hashes are completely non-ordered
  • you would initialize and create an empty beginning hash like this: <hash_name> = {}
  • you would add values to a hash like this: <hash_name> = {’<key>’ => ‘<value>’, ‘<key>’ => ‘<value>’}
  • to pull values out of the hash you simply reference the key of the hash: <hash_name>[<key>]
  • to remove an entire hash you simply re-initialize it back to an empty hash: <hash_name> = {}
  • some of the methods of the hash class include the following:
    • .keys //returns all of the keys of a hash as an array
    • .values //returns all of the values a hash as an array
    • .fetch() //returns the value associated with a key
    • .values_at() //returns the values of the keys specified in a comma separated list passed to values_at()
    • .length
    • .merge() //allows you to merge two hashes together.

Logical Expressions (conditionals/if/then statements)

  • control flow is defined by the way that ruby processes statements
  • we use logical expressions when we want ruby to make a decision
  • logical statements have the following syntax:
    • if <logical_test> then
      <do_something>
      end
    • or you could use the else command
    • if <logical_test> then
      <do_something>
      else
      <do_this_instead>
      end
    • or you could use the elsif command
    • if <logical_test> then
      <do_something>
      elsif
      <do_this_instead>
      else
      <do_this_instead>
      end

Loops

  • a way in ruby to execute code more than one time
  • a simple example of a loop is: //.times is a method of the number class
    • 9.times do
      <statements>
      end
  • most of the time code blocks are placed between a do and end statement
  • you can also write code blocks on a single line by using the curly brace notation { <statements here> }
    • while <condition>
      <statements>
      end

Iterators

  • a special type of loop that will be more useful to programmers who are working with data in a database.
  • a simple example of an iterator is: //this is a nice way to loop because this iterator keeps track of the iterations
    • 9.upto(<number>) do
      <statements>
      end
  • you can track the current iteration of the loop by declaring a local variable that is only available in the loop
    • 9.upto(<number>) |<local_variable>| do
      <statements>
      end
  • there is also a .downto() method
  • there is a .step() method which allows the iteration of more than just one for each iteration
  • one of the most powerful ways to use the iterator with an array or hash or any other collection of data is to use the for each item in format
  • a simple example of iterating through an array using the each method is:
    • <array_name>.each do |<local_variable>|
      <statements>
      end
  • an even easier way of iterating through an array using the for method is:
    • for <local_variable> in <array_name>
      <statements>
      end
  • break //keyword used to break out of a loop
Sphere: Related Content

Tags: Programming


1 response so far ↓

  • 1 Raghavendra // Feb 15, 2008 at 6:16 am

    nice presentation

Leave a Comment