If you have a C-like syntax language background like me, planned to learn Ruby for years, but never get started (with a valid reason, I know :-) Something quick to share with you today: a short highlights of Ruby expression.
Every statement returns a value
- Every statement is an expression. You can code something like this:
a = b = 1 # => 1 bar = "spam" foo = if bar == "spam" "great!" else "keep going" end p foo # => "great!" defined? var # => nil var = var || "default value" # => "default value"
- If
varis not defined,defined? varreturnsnil. Otherwise, it returns thevardescription. - It's a handy tool when learning the language in
irb. But just curious how it is used in production code..
- Swapping values of two variables is easy, like Python
a = 1 b = 2 a, b = b, a # => a=2, b=1 - Or you can perform neat stunts using splat (asterisk prefix)
list = [1,2,3,4] first, *, sec_last, last = list # => first=1, sec_last=3, last=4 first, *middle, last = list # => first=1, middle=[2,3], last=4 # more stunts.. a, b, c, d = *(1..2), *[3, 4] # => a=1, b=2, c=3, d=4
- Everything is
true, exceptnil,false. - That means
0and''is evaluated totrue! Beeee careful.
- You can use normal
if..elsif..else..endorunless..endstatements - or append
if/unlessto a statement, like Perlprocess(order) if order.valid?
case statement
- Great to see there is no
breaks :) - Note that,
whenstatement uses===operator (case equality) to perform matching.case command when "debug" dump_debug_info dump_symbols when /p\s+(\w+)/ dump_variable($1) when "quit", "exit" exit else print "Illegal command: #{command}" end
- Ruby provides
while..endanduntil..end, or you can appendwhile/untilto a statement:puts a += 1 until a == 100 - We may use
for..in..endandloop do..endto iterate through a list, but I believe many Rubyists preferlist.each{}.
- Block introduces new scope. Block is a chunk of codes enclosed within
{..}ordo..end. A few ground rules:- New variable defined in a block is not visible outside the block.
- Variables exist before a block, can be accessed within the block (think closure).
- A block's parameter will shadow a variable outside the block with same name.
defined? local # => nil x = y = -1 [1,2,3].each do |x| local = y = x end defined? local # => nil p x # => -1 p y # => 3 - Built-in expressions such as
if, unless, while, until, fordo not use block. So they do not introduce new scope. As a result, new variables defined in awhileloop, will continue to exist after the loop.
Learn Ruby?
My rubyist friend, Yasith recommended to start with this book: Programming Ruby. The latest edition Programming Ruby 1.9 is available on bookshelf.
No comments:
Post a Comment