Code Monkey home page Code Monkey logo

ruby-is-special's Introduction

Ruby is Special!

Some general notes, gotchas, and things I love about Ruby. Note that this is a work in progress. I'll add to it as I get time, and as Ruby continues to unveil her mysterious wonders...

Uniquely Ruby

A few of the things that make Ruby different from other programming languages.

Everything is an Object

That includes numbers; therefore numbers have methods associated with them. For instance, the methods .times and .even? as demonstrated below.

3.times {print "Hola!"} # prints Hola!Hola!Hola!
puts 12.even? # prints true

Symbols

Blocks

Inline if

Instead of using a simple if block, Ruby lets you write a statement that is only evaluated if the statement following it is true. So instead of this:

if !x.empty?
  puts "x is not empty"
end

You can write this:

puts "x is not empty" if !x.empty?

Unless

Ruby also allows you to use unless instead of if !. You can use it in block form:

unless x.empty?
  puts "x is not empty"
end

Or in inline form like the if statement above:

  puts "x is not empty" unless x.empty?

General Notes

Some basics about Ruby types, syntax, conventions, etc.

Typing

Ruby is a dynamically-typed language so you do not need to declare a type for each variable, and the same variable can hold different types throughout its lifetime.

x = "Hello World"
x = 44
x = ["Hiya", "Hola", "Bonjour"]

Conventions

Naming

  • Variables should be named using snake_case: new_variable.
  • Methods should be named using snake_case as well: def new_method(input_value)
  • Methods that return a boolean value should end in a ?: def is_cool?(temp)
  • Setter methods should end in a =: def name=(input_value)
  • Class and module names follow CapWords (or CamelCase) convention: class NewClass
  • File names follow snake_case: new_file.rb

Methods

If a method doesn't take an argument, it is conventional to leave off the () at the end of both the method call and the method definition.

def say_hello
  puts "Hello!"
end

say_hello  # prints Hello!

Ternary Operator

Ruby, like Java and many other languages, allows you to write a succinct "if/else" conditional statement using the ternary operator, like so:

params[:session][:remember_me] == '1' ? remember(user) : forget(user)

An expression that uses the ternary operator consists of the following parts:

boolean? ? do_one_thing : do_something_else

If the boolean expression evaluates to true, do the thing listed immediately following the ?; if it evaluates to false, do the thing listed after the :.

In Ruby, there are a couple other cool things you can do with the ternary operator. You can use it in an assignment:

var = boolean? ? foo : bar

And you can use it as a function's return value:

def foo
  do_stuff
  boolean? ? "bar" : "baz"
end

Since Ruby implicitly returns the value of the last expression in a function, here the foo method returns "bar" or "baz" depending on whether boolean? is true or false.

Gotcha!

Unexpected things about Ruby. Good to know these things to avoid bugs/logical errors.

Truthy and Falsey

Everything except nil and false is truthy in a boolean context in Ruby.

Single-quoted Strings

  • Unlike with double-quoted strings, Ruby won’t interpolate into single-quoted strings.
name = "Thom"
puts "#{name} Paine"  # prints Thom Paine
puts '#{name} Paine'  # prints #{name} Paine
  • Single-quoted strings are often useful because they are truly literal, containing exactly the characters you type. E.g.,
name = 'Thom Paine \n'
print name  # prints Thom Paine \n
name = "Thom Paine \n"
print name  # prints Thom Paine and then a newline

Array Methods

The built-in array methods do not change the array, but rather return a modified copy of the array.

a = [8, 23, 15]
puts a.sort  # prints [8, 15, 23]
puts a  # prints [8, 23, 15]

If you want to mutate the array, add a bang (!) to the end of the method:

a = [8, 23, 15]
puts a.sort!  # prints [8, 15, 23]
puts a  # prints [8, 15, 23]

Assignment in a boolean clause

Let's look at a potentially confusing statement:

if (user_id = session[:user_id])

Note that this is not a comparison (which would use == instead of a single equals sign), but rather this means "If session of user id exists (while setting user id to session of user id)..."

Rails Notes

A few Rails-specific notes/factoids.

  • The distinction between the two types of embedded Ruby is that <% ... %> executes the code inside, while <%= ... %> executes the code inside and inserts the result into the template.

Resources

Lots of amazing resources informed this reference, including the following:

Head First Ruby

Ruby on Rails Tutorial

ruby-is-special's People

Contributors

seraries avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.