JVK
JVK

Reputation: 3912

Understanding Ruby (Sinatra) - very very basic

I was looking at Sinatra and trying to understand the syntax:

require 'sinatra'

get '/' do
  "Hello, World!"
end

I understand it does this:

This is a ‘Route’. Here, we’re telling Sinatra that if the home, or root, URL '/' is requested, using the normal GET HTTP method, to display “Hello, World!”

But what is happening the Ruby language?

  1. What does this syntax mean: get '/'? Is get a method and '/' a parameter to it? If it is method, then in Ruby, I can call a method as methodname (parameter) {}. What is { } there for?
  2. I usually understand do and end as { }, which are kinds of enclosures to function bodies.
  3. Between do and end we have "Hello, World!" so is it a statement? What I mean is, it is getting printed, but we did not call it as print "Hello, World!", so what is going on?
  4. It seems get is a method defined in Sinatra, but if I add a gem, where there is a get method already defined, then how do I know which 'get' method it would call? Or, does it refer to the HTTP get method?

I am sorry if this question sounds very basic, but I want to get through it before I move forward.

Upvotes: 1

Views: 220

Answers (2)

Michel
Michel

Reputation: 726

For the "perfect" response, I suggest you have a look at the book "Sinatra Up and Running" by Alan Harris and Konstantin Haase.

http://shop.oreilly.com/product/0636920019664.do

Pages 6 and 7 explain how the line "get '/' do" is in fact a method call.

And you can view this 2 pages with Google Preview.

Upvotes: 0

zellio
zellio

Reputation: 32484

May I suggest going through a tutorial on ruby before tackling a larger problem like sinatra which is a fairly specialized library.

A good place to start is with the Ruby Koans

As for your questions.

  1. get is a method. '/' is its argument. and do ... end denotes a block in ruby just like {} would.
  2. Yeah that's what do ... end are
  3. Blocks in Ruby return the last value calculated by default so in the is case having a string is the same as having return "String".
  4. If you are getting a namespace collision, Ruby will complain. In this case get is the sinatra defined method get. Abstractly it stands for an HTTP GET request against the server.

Upvotes: 1

Related Questions