I just read the following code:
class Dir
def self.create_uniq &b ### Here, & should mean b is a block
u = 0
loop do
begin
fn = b[u] ### But, what does b[u] mean? And b is not called.
FileUtils.mkdir fn
return fn
rescue Errno::EEXIST
u += 1
end
end
io
end
end
I put my confusion as comment in the code.
The usage of "%I" is just to create hash keys from an array of strings, separated by whitespaces.
Instance variables Examples: @foobar. The variable which name begins which the character ` @ ', is an instance variable of self . Instance variables are belong to the certain object. Non-initialized instance variables has value nil .
What's a Symbol in Ruby? A symbol is a unique instance of the Symbol class which is generally used for identifying a specific resource. A resource can be: a method.
Ruby symbols are created by placing a colon (:) before a word. You can think of it as an immutable string. A symbol is an instance of Symbol class, and for any given name of symbol there is only one Symbol object. :apple.object_id.
Defining method with &b
on the end allows you to use block passed to the method as Proc
object.
Now, if you have Proc
instance, []
syntax is shorthand to call
:
p = Proc.new { |u| puts u }
p['some string']
# some string
# => nil
Documented here -> Proc#[]
The & prefix operator allow a method to capture a passed block as a named parameter. e.g:
def wrap &b
3.times(&b)
print "\n"
end
now if you call above method like this:
wrap { print "Hi " }
then output would be:
Hi Hi Hi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With