1. Why is there an equals sign in the code "def
self.run=(flag)" and what
does it do?
Methods can have an equals sign at the end of their name. Ruby calls
these methods when you write something that LOOKS like you're assigning
to a property:
class Foo
def bar=( new_value )
puts "I'm going to set a new value of #{new_value}!"
@some_var = new_value
end
end
f = Foo.new
f.bar = "Hello World"
#=> I'm going to set a new value of Hello World!
2. Why is there an equals sign in the code "@run ||= false"
and what does
it do?
a ||= b
is shorthand for
a = a || b
just like a += b is shorthand for a = a + b
Because the || operator does not return a boolean value, but rather the
first operand that isn't a non-truth value, the above code is equivalent
to:
@run = if @run
@run
else
false
end
In practical application, what it's saying is:
"If the @run variable is nil or false, set the value to false".
or precisely:
"If the @run variable is nil (probably because it hasn't been assigned
to a value yet), please set it to false."
5. What does "$0 != "-e" && $0" mean and do?
$0 is a global variable that holds the name of the currently-running
script.
If you run "ruby foo.rb" then $0 will be the string "foo.rb".
If you run ruby with the -e option, it will evaluate the string you
supply as ruby code. For example, "ruby -e 'p 1+1'" will print 2.
When run like this, $0 is set to "-e", because there is no file name.
SO, the above code is saying "If $0 isn't -e, then the name of the
currently-running file." Like ||, the && operator doesn't actually
return true or false, it returns the value of the left side if the left
side is a non-truth value (false or nil), or the value of the right
side.
The $0!="-e"&&$0 bit is a terse (obfuscated?) way of saying "if the
script being run is off of the command line, use a value of false;
otherwise, use the value of the currently-running file name"