I have a background from languages which use {} to say that these are "block of statements" but i am learning ruby and really confused how it being done there.
So lets say in C i have
if ( condition )
{
statement1;
statement2;
}
else if (condition)
{
statement1;
statement2;
// nested if
if (condition)
{
dosomethinghere;
}
}
else
{
statement1;
statement2开发者_运维问答;
}
How i can put this code in ruby? and also mention how to understand synomenous of "{}" in ruby, thanks.
Well, to answer your first question:
if ( condition )
statement1
statement2
elsif (condition)
statement1
statement2
// nested if
if (condition)
dosomethinghere
end
else
statement1
statement2
end
The syntax rule for if
statement is:
if expr [then]
expr...
[elsif expr [then]
expr...]...
[else
expr...]
end
Where everything between []
is optional
However, and in other direction, you can also create and pass code blocks, check this post to read more about this topic.
The ruby syntax for if is:
if condition body else alternativa body end
Or
if condition then body else alternative body end
It's the same for while loops except with do
instead of then
.
{
and }
are used to pass anonymous functions (confusingly called "blocks" in ruby) as arguments to methods.
I'd suggest getting a decent book and sitting down and reading the first few chapters this should cover everything you asked here and a lot more. I'd suggest http://oreilly.com/catalog/9780596529864 although if you're trying to get something done really quick http://www.troubleshooters.com/codecorn/ruby/basictutorial.htm is quite a good brief intro to get you started.
in Ruby, the opening brace is implied after an if
. to close the block, you use an end
instead of a close brace. the only other difference is you use elsif (condition)
instead of else if (condition)
.
If you're thinking "how do I create a new variable scope in Ruby"? ie:
{
var myvar = 1;
}
myvar = 2; // compile error because myvar isn't in this scope!
I'm not really sure how you would do that.
try running the following:
def example(x,y)
puts "X:#{x},Y:#{y}"
if ( x == 0 ) then
puts "Its true"
elsif (x == 1)
puts "Its not true"
puts "it certainly isn't"
if (y == 0) then
puts "i'm the nested if"
end
else
puts "i made it to the default case"
puts "freedom"
end
puts
end
example(0,0)
example(1,0)
example(1,1)
example(2,2)
If you want a scope you can define your own scope
method:
def scope
yield
end
# use like this
scope {
x = 5
puts x #=> 5
}
x #=> undefined local variable
EDIT: for a better approach to 'scopes' in Ruby 1.9 see: http://banisterfiend.wordpress.com/2010/01/07/controlling-object-scope-in-ruby-1-9/
精彩评论