Jump to content

User:WillWare/Learning Ruby

From Wikipedia, the free encyclopedia

I've been starting to learn Ruby on Rails and I realize I need a few notes about the Ruby language itself.

Ruby tutorials

[edit]

Variable name conventions

[edit]
  • No leading punctuation indicates a local variable of the function or method. It lasts only until you leave the function or method.
  • A single at-sign (e.g. "@data") indicates an instance variable. Each instance of the class has its own value for this variable.
  • A double at-sign (e.g. "@@sharedData") indicates a class variable, shared by all instances of the class.
  • A dollar sign (e.g. "$DATA") indicates a global variable.
  • A name beginning with a capital letter (e.g. "PI") indicates a constant.

Blocks

[edit]

Much of Ruby's syntax is pretty obvious by comparison with other languages, but one piece of syntax is worth a look.

sum = 0
4.step(12, 2) do |x|
  sum += x
end
puts "This adds up to " + sum.to_s

This adds up the even numbers from 4 to 12, yielding 40.

  • The first tricky thing is "4.step(12, 2)", which constructs a list starting with 4, incrementing by 2, and ending with 12.
  • The second tricky thing is that do |x| ...stuff... end defines a block, sort of an anonymous function, whose argument is x.
  • The last piece is "to_s", which is an explicit cast of an object to a string.

Functions return the last expression

[edit]

Like Lisp, Ruby doesn't distinguish between statements and expressions. If a function or method has a series of expressions, the last one becomes the return value, like the "let" construct in Scheme. If there are more Lisp/Scheme-like constructs in Ruby, I'm going to like it.

irb(main):005:0> def blorp
irb(main):006:1>   3
irb(main):007:1>   4
irb(main):008:1>   5
irb(main):009:1> end
=> nil
irb(main):010:0> puts blorp
5
=> nil

Some things are still mysterious

[edit]

What is going on here?

map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get }

Are we passing three separate arguments to map.resources, or a single hash with three keys? I tried this.

irb(main):001:0> puts :x, :a => { :b => "c" }, :d => { :e => "f" }
x
abcdef
=> nil

The ":x" is taken as the first argument, and the rest is taken as a hash with two keys. So we're passing in two arguments, a symbol and a hash.

irb(main):004:0> puts :x, :a => { :b => "c" }, :d => { :e => "f" }, :y
SyntaxError: compile error
(irb):4: syntax error, unexpected '\n', expecting tASSOC
	from (irb):4
	from :0

This gives an error because ":y" is not continuing the hash.

Everything is so goddamn awkward in this language

[edit]
foo = FooController.new
foo.events

for i in 1..10
  puts i
end