Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Code explained

Tags:

ruby

Could somebody please explain this piece of Ruby code:

def add_spec_path_to(args) # :nodoc:
  args << {} unless Hash === args.last
  args.last[:spec_path] ||= caller(0)[2]
end

I have seen the << operator used for concatenation strings or as a bitwise operator in other languages but could somebody explain it in this context. Is it somehow appending a blank lamda onto args or am I totally wrong?

I can also see it used like this:

before_parts(*args) << block

Is the Hash a keyword?

I am also unsure of what the ||= operator is saying.

I am equally in the dark as to what caller(0)[2] is.

like image 601
dagda1 Avatar asked Mar 04 '09 07:03

dagda1


People also ask

What does Ruby coding do?

Ruby is mainly used to build web applications and is useful for other programming projects. It is widely used for building servers and data processing, web scraping, and crawling. The leading framework used to run Ruby is Ruby on Rails, although that's not the only one.

Is learning Ruby code hard?

It's a model-view-controller framework that provides default database, web page, and web service structures. And no, it's not hard to learn at all! Between its thriving community and its straightforward workflow, Ruby on Rails may be one of, if not THE, most beginner-friendly frameworks in existence.

Is Ruby a coding language?

More specifically, Ruby is a scripting language designed for front- and back-end web development, as well as other similar applications. It's a robust, dynamically typed, object-oriented language, with high-level syntax that makes programming with it feel almost like coding in English.


1 Answers

I'm presuming that args is an Array.

Hash is the name of a class - the first line pushes an empty hash {} onto args unless the last element of args is already a Hash (the === operator for classes tests whether an object is of a certain class).

The ||= operator is similar to the += operator: it's more or less equivalent to:

args.last[:spec_path] = args.last[:spec_path] || caller(0)[2]

So, it will set args.last[:spec_path] if and only if it is currently unset.

The caller method returns info about the calling method.

like image 86
Sophie Alpert Avatar answered Nov 12 '22 14:11

Sophie Alpert