These questions & answers are from Stack overflow. We summarized them based on the the number of the votes & views to make sure these problems are seen more often.

1. I am having a hard time understanding attr_accessor s in Ruby, can someone explain them to me? I have done tons of Google searches, just can't understand them fully.

457 Votes & 189,000 Views

Top Voted Stack Overflow Answer

Let's say you have a class Person . class Person end person = Person . new person . name # => no method error Obviously we never defined method name . Let's do that. class Person def name @name # simply returning an instance variable @name end end person = Person . new person . name # => nil person . name = "Dennis" # => no method error Aha, we can read the name, but that doesn't mean we can assign the name. Those are two different methods. Former called reader and latter called writer. We didn't create the writer yet so let's do that. class Person def name @name end def name =( str ) @name = str end end person = Person . new person . name = 'Dennis' person . name # => "Dennis" Awesome. Now we can write and read instance variable @name using reader and writer methods. Except, this is done so frequently, why waste time writing these methods every time? We can do it easier. class Person attr_reader : name attr_writer : name end Even this can get repetitive. When you want both reader and writer just use accessor! class Person attr_accessor : name end person = Person . new person . name = "Dennis" person . name # => "Dennis" Works the same way! And guess what: the instance variable @name in our person object will be set just like when we did it manually, so you can use it in other methods. class Person attr_accessor : name def greeting "Hello #{@name}" end end person = Person . new person . name = "Dennis" person . greeting # => "Hello Dennis" That's it. In order to understand how attr_reader , attr_writer , and attr_accessor methods actually generate methods for you, read other answers, books, ruby docs.

2. What is this double-colon :: all about? E.g. Foo::Bar .

=======================================================================================================================================

I found a definition:

The :: is a unary operator that allows: constants, instance methods and class methods defined within a class or module, to be accessed from anywhere outside the class or module.

but that just leads to more questions. What good is scope (private, protected) if you can just use ::to expose anything?

225 Votes & 43,000 Views

Top Voted Stack Overflow Answer

:: is basically a namespace resolution operator. It allows you to access items in modules, or class-level items in classes. For example, say you had this setup: module SomeModule module InnerModule class MyClass CONSTANT = 4 end end end You could access CONSTANT from outside the module as SomeModule::InnerModule::MyClass::CONSTANT . It doesn't affect instance methods defined on a class, since you access those with a different syntax (the dot . ). =======================================================================================================================================

3. Why is it bad style to rescue Exception => e in Ruby?

Ryan Davis’s Ruby QuickRef says (without explanation):

Don’t rescue Exception. EVER. or I will stab you.

Why not? What’s the right thing to do?

456 Votes & 114,846 Views

Top Voted Stack Overflow Answer

Exception is the root of Ruby's exception hierarchy, so when you rescue Exception you rescue from everything, including subclasses such as SyntaxError , LoadError , and Interrupt . Rescuing Interrupt prevents the user from using CTRL C to exit the program. Rescuing SignalException prevents the program from responding correctly to signals. It will be unkillable except by kill -9 . Rescuing SyntaxError means that eval s that fail will do so silently. All of these can be shown by running this program, and trying to CTRL C or kill it: loop do begin sleep 1 eval "djsakru3924r9eiuorwju3498 += 5u84fior8u8t4ruyf8ihiure" rescue Exception puts "I refuse to fail or be stopped!" end end Rescuing from Exception isn't even the default. Doing begin # iceberg! rescue # lifeboats end does not rescue from Exception , it rescues from StandardError . You should generally specify something more specific than the default StandardError , but rescuing from Exception broadens the scope rather than narrowing it, and can have catastrophic results and make bug-hunting extremely difficult. If you have a situation where you do want to rescue from StandardError and you need a variable with the exception, you can use this form: begin # iceberg! rescue => e # lifeboats end which is equivalent to: begin # iceberg! rescue StandardError => e # lifeboats end One of the few common cases where it’s sane to rescue from Exception is for logging/reporting purposes, in which case you should immediately re-raise the exception: begin # iceberg? rescue Exception => e # do some logging raise e # not enough lifeboats ;) end





4. How best to generate a random string in Ruby?

=======================================================================================================================================

I'm currently using the following to generate an 8 character pseudo random upper case string [A-Z]

value = ""; 8.times{value << (65 + rand(25)).chr}

but it looks junky, and since it isn't a single statement it can't be passed as an argument. To get a mixed case string [a-zA-Z] I further hack into it with

value = ""; 8.times{value << ((rand(2)==1?65:97) + rand(25)).chr}

433 Votes & 203,777 Views

Top Voted Stack Overflow Answer

( 0. .. 8 ). map { ( 65 + rand ( 26 )). chr }. join I spend too much time golfing. ( 0. .. 50 ). map { ( 'a' .. 'z' ). to_a [ rand ( 26 )] }. join For lots of good WTFBBQ factor. And a last one that's even more confusing, but more flexible and wastes less cycles: o = [( 'a' .. 'z' ), ( 'A' .. 'Z' )]. map { | i | i . to_a }. flatten string = ( 0. .. 50 ). map { o [ rand ( o . length )] }. join

5. Calling shell commands from Ruby

=======================================================================================================================================

How do I call shell commands from inside of a Ruby program? How do I then get output from these commands back into Ruby?

499 Votes & 229,242 Views

Top Voted Stack Overflow Answer

This explanation is based on this commented Ruby script from a friend of mine. If you want to improve the script, feel free to update it at the link. First, note that when Ruby calls out to a shell, it typically calls /bin/sh , not Bash. Some Bash syntax is not supported by /bin/sh on all systems. Ways to execute a shell script cmd = "echo 'hi'" # Sample string that can be used 1. Kernel#` , commonly called backticks – `cmd` Ways to execute a shell script1., commonly called backticks – This is like many other languages, including Bash, PHP, and Perl Returns the result of the shell command. Docs: http://ruby-doc.org/core/Kernel.html#method-i-60 value = `echo 'hi'` value = `#{cmd}` 2. Built-in syntax, %x( cmd ) 2. Built-in syntax, Following the x character is a delimiter, which can be any character. If the delimiter is one of the characters ( , [ , { , or < , the literal consists of the characters up to the matching closing delimiter, taking account of nested delimiter pairs. For all other delimiters, the literal comprises the characters up to the next occurrence of the delimiter character. String interpolation #{ ... } is allowed. Returns the result of the shell command, just like the backticks. Docs: http://www.ruby-doc.org/docs/ProgrammingRuby/html/language.html value = % x ( echo 'hi' ) value = % x [ #{cmd} ] 3. Kernel#system 3. Executes the given command in a subshell, Return: true if the command was found and ran successfully, false otherwise Docs: http://ruby-doc.org/core/Kernel.html#method-i-system wasGood = system ( "echo 'hi'" ) wasGood = system ( cmd ) 4. Kernel#exec 4. Replaces the current process by running the given external command. Return: none, the current process is replaced and never continues Docs: http://ruby-doc.org/core/Kernel.html#method-i-exec exec ( "echo 'hi'" ) exec ( cmd ) # Note: this will never be reached because of the line above Extra Advice Extra Advice $? , which is the same as $CHILD_STATUS , accesses the status of the last system executed command if you use the backticks, system() or %x{} . You can then access the exitstatus and pid properties $ ?. exitstatus More Reading http://www.elctech.com/blog/i-m-in-ur-commandline-executin-ma-commands

http://blog.jayfields.com/2006/06/ruby-kernel-system-exec-and-x.html

http://tech.natemurray.com/2007/03/ruby-shell-commands.html More Reading

6. What is the difference between include and require in Ruby?

=======================================================================================================================================

What's the difference between require and include in Ruby? If I just want to use the methods from a module in my class, should I require it or include it?

302 Votes & 113411 Views

Top Voted Stack Overflow Answer

From here: What's the difference between "include" and "require" in Ruby? Answer: The include and require methods do very different things. The require method does what include does in most other programming languages: run another file. It also tracks what you've required in the past and won't require the same file twice. To run another file without this added functionality, you can use the load method. The include method takes all the methods from another module and includes them into the current module. This is a language-level thing as opposed to a file-level thing as with require. The include method is the primary way to "extend" classes with other modules (usually referred to as mix-ins). For example, if your class defines the method "each", you can include the mixin module Enumerable and it can act as a collection. This can be confusing as the include verb is used very differently in other languages. So if you just want to use a module, rather than extend it or do a mix-in, then you'll want to use require . Oddly enough, Ruby's require is analogous to C's include , while Ruby's include is almost nothing like C's include .

7 . What's the difference between a proc and a lambda in Ruby?

=======================================================================================================================================

And when would you use one rather than the other?

90 Votes & 13061 Views

Top Voted Stack Overflow Answer