Archive for the ‘Ruby’ Category

Ruby: change to upper/lower case

"hello James!".downcase    #=> "hello james!"

Similarly, upcase capitalizes every letter and capitalize capitalizes the first letter of the string but lowercases the rest:

"hello James!".upcase      #=> "HELLO JAMES!""hello James!".capitalize  #=> "Hello james!"

If you want to modify a string in place, you can add an exclamation point to any of those methods:

string = "hello James!"
string.downcase!
string   #=> "hello james!"

Ruby: Here documents

For creating multiple-line strings, Ruby supports here documents (heredocs), a feature that originated in the Bourne shell and is also available in Perl and PHP.

To construct a here document, the << operator is followed by an identifier that marks the end of the here document. The end mark is called the terminator. The lines of text prior to the terminator are joined together, including the newlines and any other whitespace.

puts <<GROCERY_LIST
Grocery list
------------
1. Salad mix.
2. Strawberries.*
3. Cereal.
4. Milk.*

* Organic
GROCERY_LIST

The result:

$ grocery-list.rb
Grocery list
------------
1. Salad mix.
2. Strawberries.*
3. Cereal.
4. Milk.*

* Organic

If we pass the puts function multiple arguments, the string literal created from the here document is inserted into the argument list wherever the << operator appears. In the code below, the here-document (containing the four grocery items and a blank line) is passed in as the third argument. We get the same output as above.

puts 'Grocery list', '------------', <<GROCERY_LIST, '* Organic'
1. Salad mix.
2. Strawberries.*
3. Cereal.
4. Milk.*

GROCERY_LIST

You can also have multiple here documents in an argument list. We added a blank line at the end of each here document to make the output more readable.

puts 'Produce', '-------', <<PRODUCE, 'Dairy', '-----', <<DAIRY, '* Organic'
1. Strawberries*
2. Blueberries

PRODUCE
1. Yogurt
2. Milk*
3. Cottage Cheese

DAIRY

The result:

$ grocery-list.rb
Produce
-------
1. Strawberries*
2. Blueberries

Dairy
-----
1. Yogurt
2. Milk*
3. Cottage Cheese

* Organic

We have been using the puts function in our examples, but you can pass here documents to any function that accepts Strings.

Indenting

If you indent the lines inside the here document, the leading whitespace is preserved. However, there must not be any leading whitespace before the terminator.

puts 'Grocery list', '------------', <<GROCERY_LIST
    1. Salad mix.
    2. Strawberries.
    3. Cereal.
    4. Milk.
GROCERY_LIST

The result:

$ grocery-list.rb
Grocery list
------------
    1. Salad mix.
    2. Strawberries.
    3. Cereal.
    4. Milk.

If, for readability, you want to also indent the terminator, use the <<- operator.

puts 'Grocery list', '------------', <<-GROCERY_LIST
    1. Salad mix.
    2. Strawberries.
    3. Cereal.
    4. Milk.
    GROCERY_LIST

Note, however, that the whitespace before each line of text within the here document is still preserved.

$ grocery-list.rb
Grocery list
------------
    1. Salad mix.
    2. Strawberries.
    3. Cereal.
    4. Milk.

Quoting rules

You may wonder whether here documents follow single-quoting or double-quoting rules. If there are no quotes around the identifier, like in our examples so far, then the body of the here document follows double-quoting rules.

name = 'Charlie Brown'

puts <<QUIZ
Student: #{name}

1.\tQuestion: What is 4+5?
\tAnswer: The sum of 4 and 5 is #{4+5}
QUIZ

The result:

$ quiz.rb
Student: Charlie Brown

1.      Question: What is 4+5?
        Answer: The sum of 4 and 5 is 9

Double-quoting rules are also followed if you put double quotes around the identifier. However, do not put double quotes around the terminator.

puts <<"QUIZ"
Student: #{name}

1.\tQuestion: What is 4+5?
\tAnswer: The sum of 4 and 5 is #{4+5}
QUIZ

To create a here document that follows single-quoting rules, place single quotes around the identifier.

puts <<'BUS_SCHEDULES'
c:\napolean's documents\tomorrow's bus schedule.txt
c:\new documents\sam spade's bus schedule.txt
c:\bus schedules\the #9 bus schedule.txt
BUS_SCHEDULES

The result:

$ bus-schedules.rb
c:\napolean's documents\tomorrow's bus schedule.txt
c:\new documents\sam spade's bus schedule.txt
c:\bus schedules\the #9 bus schedule.txt


Source: http://en.wikibooks.org/wiki/Ruby_Programming/Here_documents

Ruby: Use R in Ruby via “rinruby”!

  >>  sample_size = 10
>>  R.eval “x <- rnorm(#{sample_size})”
>>  R.eval “summary(x)”
>>  R.eval “sd(x)”

With a here document:

require "rinruby"      
#Set all your variables in Ruby
n = 10
beta_0 = 1
beta_1 = 0.25
alpha = 0.05
seed = 23423
R.x = (1..n).entries
#Use actual R code to perform the analysis
R.eval <<EOF
  set.seed(#{seed})
  y <- #{beta_0} + #{beta_1}*x + rnorm(#{n})
  fit <- lm( y ~ x )
  est <- round(coef(fit),3)
  pvalue <- summary(fit)$coefficients[2,4]
EOF

Ruby: Case statements

print "Enter your grade: "
grade = gets.chompcase grade
when "A"
  puts 'Well done!'when "B"
  puts 'Try harder!'when "C"
  puts 'You need help!!!'else
  puts "You just making it up!"end

Sources:
 http://www.skorks.com/2009/08/how-a-ruby-case-statement-works-and-what-you-can-do-with-it/

Ruby: Loops – while, for, until, break, redo and retry

Ruby while Statement:

Syntax:

while conditional [do]
   code
end

Executes code while conditional is true. A while loop’s conditional is separated from code by the reserved word do, a newline, backslash \, or a semicolon ;.

Example:

#!/usr/bin/ruby

$i = 0
$num = 5

while $i < $num  do
   puts("Inside the loop i = #$i" )
   $i +=1end

This will produce the following result:

Inside the loop i = 0Inside the loop i = 1Inside the loop i = 2Inside the loop i = 3Inside the loop i = 4

Ruby while modifier:

Syntax:

code while condition

OR

begin 
  code 
end while conditional

Executes code while conditional is true.

If a while modifier follows a begin statement with no rescue or ensure clauses, code is executed once before conditional is evaluated.

Example:

#!/usr/bin/ruby

$i = 0
$num = 5begin
   puts("Inside the loop i = #$i" )
   $i +=1end while $i < $num

This will produce the following result:

Inside the loop i = 0Inside the loop i = 1Inside the loop i = 2Inside the loop i = 3Inside the loop i = 4

Ruby until Statement:

until conditional [do]
   code
end

Executes code while conditional is false. An until statement’s conditional is separated from code by the reserved word do, a newline, or a semicolon.

Example:

#!/usr/bin/ruby

$i = 0
$num = 5

until $i > $num  do
   puts("Inside the loop i = #$i" )
   $i +=1;end

This will produce the following result:

Inside the loop i = 0Inside the loop i = 1Inside the loop i = 2Inside the loop i = 3Inside the loop i = 4Inside the loop i = 5

Ruby until modifier:

Syntax:

code until conditional

OR

begin
   code
end until conditional

Executes code while conditional is false.

If an until modifier follows a begin statement with no rescue or ensure clauses, code is executed once before conditional is evaluated.

Example:

#!/usr/bin/ruby

$i = 0
$num = 5begin
   puts("Inside the loop i = #$i" )
   $i +=1;end until $i > $num

This will produce the following result:

Inside the loop i = 0Inside the loop i = 1Inside the loop i = 2Inside the loop i = 3Inside the loop i = 4Inside the loop i = 5

Ruby for Statement:

Syntax:

for variable [, variable ...] in expression [do]
   code
end

Executes code once for each element in expression.

Example:

#!/usr/bin/ruby

for i in 0..5
   puts "Value of local variable is #{i}"end

Here, we have defined the range 0..5. The statement for i in 0..5 will allow i to take values in the range from 0 to 5 (including 5). This will produce the following result:

Value of local variable is 0Value of local variable is 1Value of local variable is 2Value of local variable is 3Value of local variable is 4Value of local variable is 5

for…in loop is almost exactly equivalent to:

(expression).each do |variable[, variable...]| code end

except that a for loop doesn’t create a new scope for local variables. A for loop’s expression is separated from code by the reserved word do, a newline, or a semicolon.

Example:

#!/usr/bin/ruby

(0..5).each do |i|
   puts "Value of local variable is #{i}"end

This will produce the following result:

Value of local variable is 0Value of local variable is 1Value of local variable is 2Value of local variable is 3Value of local variable is 4Value of local variable is 5

Ruby break Statement:

Syntax:

break

Terminates the most internal loop. Terminates a method with an associated block if called within the block (with the method returning nil).

Example:

#!/usr/bin/ruby

for i in 0..5
   if i > 2 then
      break
   end
   puts "Value of local variable is #{i}"end

This will produce the following result:

Value of local variable is 0Value of local variable is 1Value of local variable is 2

Ruby next Statement:

Syntax:

next

Jumps to next iteration of the most internal loop. Terminates execution of a block if called within a block (with yield or call returning nil).

Example:

#!/usr/bin/ruby

for i in 0..5
   if i < 2 then
      next
   end
   puts "Value of local variable is #{i}"end

This will produce the following result:

Value of local variable is 2Value of local variable is 3Value of local variable is 4Value of local variable is 5

Ruby redo Statement:

Syntax:

redo

Restarts this iteration of the most internal loop, without checking loop condition. Restarts yield or call if called within a block.

Example:

#!/usr/bin/ruby

for i in 0..5
   if i < 2 then
      puts "Value of local variable is #{i}"
      redo
   endend

This will produce the following result and will go in an infinite loop:

Value of local variable is 0Value of local variable is 0............................

Ruby retry Statement:

Syntax:

retry

If retry appears in rescue clause of begin expression, restart from the beginning of the 1begin body.

begin
   do_something # exception raisedrescue
   # handles error
   retry  # restart from beginningend

If retry appears in the iterator, the block, or the body of the for expression, restarts the invocation of the iterator call. Arguments to the iterator is re-evaluated.

for i in 1..5
   retry if some_condition # restart from i == 1end

Example:

#!/usr/bin/ruby

for i in 1..5
   retry if  i > 2
   puts "Value of local variable is #{i}"end

This will produce the following result and will go in an infinite loop:

Value of local variable is 1Value of local variable is 2Value of local variable is 1Value of local variable is 2Value of local variable is 1Value of local variable is 2............................

Sources:
http://www.tutorialspoint.com/ruby/ruby_loops.htm
Wikipedia

Ruby: If, Else If, Ternary (shortened if statement)

The Ruby language has a very simple control structure that is easy to read and follow.

If syntax

if var == 10
print “Variable is 10″
end

If Else Syntax

if var == 10
print “Variable is 10″
else
print “Variable is something else”
end

If Else If Syntax

Here’s the key difference between Ruby and most other languages. Note that “else if” is actually spelled “elsif” without the e.

if var == 10
print “Variable is 10″
elsif var == “20”
print “Variable is 20″
else
print “Variable is something else”
end

Ternary (shortened if statement) Syntax

Ternary syntax is the same in Ruby as most languages. The following sample will print “The variable is 10″ if var is equal to 10. Otherwise it will print “The variable is Not 10″.

print “The variable is ” + (var == 10 ? “10” : “Not 10″)

Ruby: gets, gets.chomp

 

gets basically gets user input from stdin and returns a string which is passed to chomp

chomp returns a new String with the given record separator removed from the end of str (if present).

Lets say your program is

puts "Your Name: "
name = gets.chomp
puts "Hi, " + name + "!"

This is the output when you type in the name

Your Name: 
Jason
Hi, Jason!

Then the sequence of events is:

  1. Prints “Your Name: ” to the screen with the newline.
  2. Gets the input from the user
  3. Removes the last character since no seperator is specified.
  4. Assigns it to name
  5. Prints the greeting
"hello".chomp            #=> "hello"
"hello\n".chomp          #=> "hello"
"hello\r\n".chomp        #=> "hello"
"hello\n\r".chomp        #=> "hello\n"
"hello\r".chomp          #=> "hello"
"hello \n there".chomp   #=> "hello \n there"
"hello".chomp("llo")     #=> "he"

Ruby: Call Bash commands, run shell scripts

http://stackoverflow.com/questions/2232/calling-bash-commands-from-ruby

Ways to execute a shell script

cmd = "echo 'hi'" # Sample string that can be used

1. Kernel#`, commonly called backticks – `cmd`

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 )

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

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

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 beacuse of the line above

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 %{}. You can then access the exitstatus and pid properties

$?.exitstatus

More Reading

Rails: Add Authentication to Your Ruby on Rails Website in 4 Easy Steps

Step 1
In the terminal:

gem install Devise
bundle install
rails generate devise:install
rails generate devise user
rake db:migrate

Step 2
In seeds.rb:

user = User.create(email: 'name@name.com', password: 'password1', password_confirmation: 'password1')

Step 3
In the terminal:

rake db:seed

A route will be automatically created by the devise gem

Step 4

In _topnav.html.erb:
Add an if statement to check if the user is logged in:

if user_signed_in?

rubylang

Rails: Migration Files

When you generate a model in Ruby on Rails

rails generate model somename

A migration table is also generated.

The Migration is a table that describes a database and the information it holds in columns.
rubylang