What does the : mean in rails before a variable name? - ruby

For example, : symbol - I'm trying to work out what the : means, and how it differs, say, for example, from # and also from no symbol whatsoever.
If there's a guide that would be really helpful!

It's a symbol, which is a Ruby language construct.
Symbols are similar to strings, but this blog post explains the details.
# means an instance variable on the class: it's basically a variable that's shared among all methods on an instance of a class. It has no relation to :.

: denotes that you are using a symbol.
# is an instance variable - basically a variable that is set once and can be used through a ruby process until it is done.
Plain old variable_name is a local variable and that variable is only good for as long as that method is called.
As for guides, you should read up on ruby basics or take a look at the something like this

# is an ivar
: is an symbol (think it like a COSTANT in C, but without any numerical value)

http://rubylearning.com/satishtalim/ruby_symbols.html and http://www.troubleshooters.com/codecorn/ruby/symbols.htm are 2 well written guides (second one might be a bit old, but most of it applies in Ruby 1.9 too).
You might also want to check the official documentation on Symbol at http://www.ruby-doc.org/core/classes/Symbol.html

Related

Does attr_accessor require using symbols as variables in Ruby?

Every example of attr_accessors I've seen uses a symbol (:var) as the variable.
Is this a requirement of using attr_accessorand, if so, why? If not, why is it such a common practice?
Module#attr_accessor
attr_accessor(symbol, ...) → nil
attr_accessor(string, ...) → nil (newly introduced in Ruby 2.1)
Defines a named attribute for this module, where the name is symbol.id2name, creating an instance variable (#name) and a corresponding access method to read it. Also creates a method called name= to set the attribute. String arguments are converted to symbols.
Is this a requirement of using attr_accessor?
No, you are allowed with symbols as well as strings.
Read this - Understanding Ruby symbol as method call
While the current version of ruby (2.1) permits passing a string (as mentioned by #ArupRakshit), older versions of ruby did not (2.0 and prior). As such, any code that isn't relying on ruby 2.1 (and that would be almost everything) will need to pass symbols.
Aside for this, in most cases you'd want to be passing symbols anyhow, as they are atomic, have less overhead, and are semantically more in line with attribute definition than strings are.

Naming convention for syntactic sugar methods

I'm build a library for generic reporting, Excel(using Spreadsheet), and most of the time I'll be writing things out on the last created worksheet (or active as I mostly refer to it).
So I'm wondering if there's a naming convention for methods that are mostly sugar to the normal/unsugared method.
For instance I saw a blog post, scroll down to Composite, a while ago where the author used the #method for the sugared, and #method! when unsugared/manual.
Could this be said to be a normal way of doing things, or just an odd implementation?
What I'm thinking of doing now is:
add_row(data)
add_row!(sheet, data)
This feels like a good fit to me, but is there a consensus on how these kinds of methods should be named?
Edit
I'm aware that the ! is used for "dangerous" methods and ? for query/boolean responses. Which is why I got curious whether the usage in Prawn (the blog post) could be said to be normal.
I think it's fair to say that your definitions:
add_row(data)
add_row!(sheet, data)
are going to confuse Ruby users. There is a good number of naming conventions is the Ruby community that are considered like a de-facto standard for naming. For example, the bang methods are meant to modify the receiver, see map and map!. Another convention is add the ? as a suffix to methods that returns a boolean. See all? or any? for a reference.
I used to see bang-methods as more dangerous version of a regular named method:
Array#reverse! that modifies array itself instead of returning new array with reversed order of elements.
ActiveRecord::Base#save! (from Rails) validates model and save it if it's valid. But unlike regular version that return true or false depending on whether the model was saved or not raises an exception if model is invalid.
I don't remember seeing bang-methods as sugared alternatives for regular methods. May be I'd give such methods their own distinct name other then just adding a bang to regular version name.
Why have two separate methods? You could for example make the sheet an optional parameter, for example
def add_row(sheet = active_sheet, data)
...
end
default values don't have to just be static values - in this case it's calling the active_sheet method. If my memory is correct prior to ruby 1.9 you'd have to swap the parameters as optional parameters couldn't be followed by non optional ones.
I'd agree with other answers that ! has rather different connotations to me.

Why aren't the arguments to File.new symbols instead of strings?

I was wondering why the people who wrote the File library decided to make the arguments that determine what mode the file is opened in strings instead of symbols.
For example, this is how it is now:
f = File.new('file', 'rw')
But wouldn't it be a better design to do
f = File.new('file', :rw)
or even
f = File.new(:file, :rw)
for example? This seems to be the perfect place to use them since the argument definitely doesn't need to be mutable.
I am interested in knowing why it came out this way.
Update: I just got done reading a related question about symbols vs. strings, and I think the consensus was that symbols are just not as well known as strings, and everyone is used to using strings to index hash tables anyway. However, I don't think it would be valid for the designers of Ruby's standard library to plead ignorance on the subject of symbols, so I don't think that's the reason.
I'm no expert in the history of ruby, but you really have three options when you want parameters to a method: strings, symbols, and static classes.
For example, exception handling. Each exception is actually a type of class Exception.
ArgumentError.is_a? Class
=> True
So you could have each permission for the stream be it's own class. But that would require even more classes to be generated for the system.
The thing about symbols is they are never deleted. Every symbol you generate is preserved indefinitely; it's why using the method '.to_sym' lightly is discouraged. It leads to memory leaks.
Strings are just easier to manipulate. If you got the input mode from the user, you would need a '.to_sym' somewhere in your code, or at the very least, a large switch statement. With a string, you can just pass the user input directly to the method (if you were so trusting, of course).
Also, in C, you pass a character to the file i/o method. There are no Chars in ruby, just strings. Seeing as how ruby is built on C, that could be where it comes from.
It is simply a relic from previous languages.

Ruby's :yields:

I was looking through some tab-completions that were automatically set up for my editor, and I found one where y was mapped to:
:yields: arguments
What is this syntax called, when, where, how and for what is this used?
This is one of the many directives supported by the RDoc documentation tool. It is used to document the arguments that get passed to a block.

Why are methods in Ruby documentation preceded by a hash sign?

When I see any Ruby method printed in text, it usually appears as:
Class#method
or
#method
Now, I would use:
Class.method
Why are all Ruby methods preceded by a pound sign? Is there any reason for it?
Note that the convention is:
Class#method
rather than
object#method
In code you would have object.method, if object was an instance of class. The # convention is not used in code.
From the RDoc documentation:
Use :: for describing class methods, # for describing instance methods, and use . for example code.
The # notation is used to refer to the canonical instance method, like String#upcase. The . notation is used to refer to the method of a particular instance, like mystring.upcase. The distinction is made to not imply that a class method 'upcase' exists.
I just realized that none of the other answers touch the most trivial aspect of the question: why the # sign?
I have two theories:
It might come from Smalltalk, where symbols are written #sym (instead of :sym) as they are in Ruby. So, if you want to refer to a Method object (as opposed to calling a method), then you would call something like Array >> #new. (The >> is itself a method that returns the method passed to it. So, in Ruby that would be Array.method :new.) In Smalltalk documentation, methods are generally referred to as Class>>method, but in Ruby Class:method would have made more sense, except that it is easily confused with Class::method. Therefore, Class#method was chosen.
My other theory is that it simply was chosen because # is the comment character in Ruby.
A definitive answer can only be given by whoever invented that convention. If it was invented for the Programming Ruby book, that would be either Dave Thomas or Andy Hunt, but I kind of doubt that. The book came out in 2001, Ruby started in 1993, how were they referring to methods before then?
From the rdoc docs (emphasis mine):
Names of classes, source files, and
any method names containing an
underscore or preceded by a hash
character are automatically
hyperlinked from comment text to their
description.
The hash notation was introduced "Programming Ruby - The Pragmatic Programmer's Guide" first published in December 2000.
The "Preface" contains "Notational Conventions":
Within the text, Fred#doIt is a reference to an instance method (doIt) of class Fred, while Fred.new [In some other Ruby documentation, you may see class methods written as Fred::new. This is perfectly valid Ruby syntax; we just happen to feel that Fred.new is less distracting to read.] is a class method, and Fred::EOF is a class constant.
This is clarified in the 2nd edition, published in October 2004:
Within the text, Fred#do_something is a reference to an instance method (in this case do_something) of class Fred, Fred.new is a class method, and Fred::EOF is a class constant. The decision to use a hash character to indicate instance methods was a tough one: it isn’t valid Ruby syntax, but we thought that it was important to differentiate between the instance and class methods of a particular class. When you see us write File.read, you know we’re talking about the class method read. When instead we write File#read, we’re referring to the instance method read.
Ruby itself uses this notation:
> rvm use 1.9.3
Using ruby-1.9.3-p551
> Object.instance_method(:initialize)
=> #<UnboundMethod: Object(BasicObject)#initialize>
It was introduced and formalised by Matz in February 2002:
commit 8210c254bee19294af67bcee0e8f5e02ebb39a60
Author: matz <matz#b2dd03c8-39d4-4d8f-98ff-823fe69b080e>
Date: Tue Feb 5 07:56:31 2002 +0000
* io.c (fptr_finalize): should raise error when fclose fails.
* eval.c (method_inspect): proper output format to distinguish
methods and singleton methods.
git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk#2046 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
All the answers above you list are correct. The one thing I would add is that the documentation style you said you would perfer
Class.method
would be easily confused with class methods. Since you can call class methods in ruby using the above syntax:
class Foo
def self.say_hi
puts "hi"
end
end
Foo.say_hi # => prints "hi"
This was mentioned in the JS version of this question, but it seems likely this nomenclature came from JavaDoc where the hash mark is translated directly into an on-page reference, e.g. href="Component.html#getComponentAt(int, int)"
heff's answer (which I can't comment on due to lack of reputation), that Ruby followed JavaDoc's example, is the best guess in my view. The JavaDoc designers needed or wanted a way to distinguish package qualifiers (which they used the dot for) from class qualifiers (which they used the hash for). JavaDoc's #see and #link tags syntax looks like this:
#see package.class#member [optional label]
{#link package.class#member [optional label]}
See the documentation of JavaDoc's package.class variant of the #see tag and the documentation of JavaDoc's #link tag, which heff already pointed to.
In JavaDoc, the package name can often be omitted, so that only the Class#member part remains, which looks equally strange as in Ruby, because Java code uses the Class.member syntax,
just as Ruby does.
It would be interesting to find out why the JavaDoc designers needed the differing syntax, while the Java compiler does fine with dots for both purposes.

Resources