Search Results for: ruby

Rails Scaffolding Guide Featured Image

What is Scaffolding in Ruby on Rails?

You may be learning Rails & you read that you have to create a “scaffold” to get your Rails application started…

Easy!

You can do this using the rails g scaffold command.

But what is scaffolding?

“Scaffolding is a temporary structure used to support a work crew to aid in the construction, maintenance and repair of buildings, bridges and all other man-made structures.” – Wikipedia

Translated into Rails:

A scaffold is a set of automatically generated files which forms the basic structure of a Rails project.

These files include:

  • A controller
  • A model
  • Views for every standard controller action (index, edit, show, new)

A new route.

And a migration to prepare your database.

Let’s see an example!

How to Use The Rails Scaffold Command

An example of scaffolding a project for a website about books would look like this.

rails g scaffold books

You should see a lot of text scrolling by, which details the files being created.

This example creates:

  • A BooksController
  • A Book model
  • A new resources :books route added to your config/routes.rb file
  • A set of testing-related files
  • View files under app/views/books (five in total)

Yes.

That’s a lot of stuff.

If you want to undo this scaffolding, right after creating it, you can use the following command.

rails d scaffold books

Where “d” means “destroy”.

Keep in mind that this will DELETE the files created by the scaffolding process.

Now:

Before you can use your scaffolded code you have to run your migrations to update your database schema.

Use the rails db:migrate command.

If no error messages show up, you’re ready! You have a basic structure for your new Rails application, or for a new feature that needs a new model, views & corresponding controller.

Next:

Run rails server.

Open your browser to localhost:3000/books & you should be able to see the results!

Rails Scaffolding With Extra Fields

By default…

Your model only gets timestamp fields, which means that the only information that you can record about your books (or whatever model you’re working with) is the time at which they were created, or updated.

Here’s how to scaffold with extra fields:

rails g scaffold books title:string author:string publication_year:integer

If you generate your scaffolding like this, you’ll have 3 fields to work with.

A title, an author, and a publication year.

That’s a bit more interesting than just having the database timestamps.

Btw.

This the same syntax we use for creating migrations with rails g migration.

Generating Specific Components

Scaffolding creates things you may not need or want right now.

But Rails is nice.

You can create individual components, like controllers, using the rails g (g for generate) command.

Examples:

  • rails g controller Fruit
  • rails g model Fruit name:string color:string (creates model + migration)
  • rails g migration CreateBook title:string year:integer (create migration only)

This ensures that the files are created using the correct naming conventions. It can also save you the work of having to manually create these files.

It’s considered good practice to delete auto-generated files that you don’t plan on using.

Summary

You’ve learned about scaffolding in Ruby so you can quickly jumpstart a new Rails application to practice with.

As you learn more you may want to let go of scaffolding.

But you can still generate individual controllers, models, or view files when you need them.

Thanks for reading! 🙂

Ruby directory operations featured image

How to Work With Directories in Ruby

Did you know that you can navigate your file system with Ruby?

With the Ruby “Dir” class.

You can list directory entries, change your current directory & even create new folders!

Here’s an example:

filenames = Dir.entries(".")

This entries method returns an array of filename entries. Every entry is a string, so you’ll need to combine this with the Ruby File class if you want to actually read these files.

Btw, this dot (.) represents the current directory.

This will be the directory your code is running from, NOT the directory you’re (in your terminal) when running the code.

Because of that…

It can be helpful to check your current directory by using the Dir.pwd method.

Now:

Let’s learn how to use the Dir class to create new directories (mkdir), rename them (mv), and find file names that follow a specific pattern (glob).

Using Ruby’s Mkdir Method To Create A New Directory

If you want to create a new folder with Ruby you can use the Dir.mkdir method.

Example:

Dir.mkdir("testing")

If given a relative path, this directory is created under the current path (Dir.pwd).

You can get a few errors:

  • Directory already exists (Errno::EEXIST)
  • Permission denied (Errno::EACCES)
  • You’re trying to create a folder under another folder that doesn’t exist yet (Errno::ENOENT)

The last error usually happens when you’re trying to create nested directories.

Or if you’re using an absolute path that doesn’t exist.

Two solutions:

  • Check if the directory exists before creating it (with Dir.exists?)
  • Use a more advanced class (next section)

Let’s keep learning!

Advanced Operations With The FileUtils Module

If you need an extra bit of horsepower you can bring in the FileUtils module from the standard library.

It includes methods like mkdir_p that create nested directories in one step.

Here’s an example:

require 'fileutils'

FileUtils.mkdir_p("/tmp/testing/a/b")

Pretty cool, right?

That’s not all, FileUtils also brings extra options for all file operations in the form of keyword arguments. Like the verbose option (prints Linux commands) & the noop (don’t change files) option.

Give it a try!

How to Rename Directories

Ruby allows you to do every operation you can do from your Operating System user interface, or from a terminal.

For example…

You can rename a directory like this:

FileUtils.mv("/tmp/a", "/tmp/b")

You’ll also need to use FileUtils here because mv is not available on the Dir class.

How to Change Your Current Directory

Because all directory operations are run from the current directory, you may want to change it.

You can use the Dir.chdir method to do this.

Example:

Dir.chdir("/tmp") { Dir.entries(".") }

This works in two ways:

  • With a block, the current directory changes only for the code inside the block
  • Without a block, it changes for all the code after the method call

Notice that chdir only works within your Ruby process, it doesn’t affect the “outside world”.

In other words…

It won’t change your shell’s working directory after your Ruby program stops running.

Listing Files & Directories With Pattern Matching

Want to find all Ruby files in a folder? An easy task with the glob method!

Example:

Dir.glob("*.rb")

You can use any other extension you want, like “.txt”, or “.yml”. Or any other text that’s part of the file name.

Want to find files inside all folders?

Yep, it’s possible:

Dir.glob("**/*.rb")

The result is an array with all the file names, including the relative path. You can remove the path & get only the file name by using the File.basename method on every file of the list that you get from glob.

Summary

You have learned how to work with directories in Ruby using the Dir & FileUtils classes.

Now it’s your turn to put this into practice.

Thanks for reading! 🙂

Java vs Ruby (Featured Image)

7 Major Differences Between Java & Ruby

How do you move from Java to Ruby?

In this guide, you’ll learn what are the major differences between the two languages to help you make the jump.

It’s great for the many people looking to move from Java/C# to Ruby.

But…

If you’re just curious about the differences, then this is also for you.

Let’s do this!

Static Typing vs Dynamic Typing

Typing style is the biggest & most notable difference when looking at code for either programming language.

Here’s the situation:

  • Java uses static typing
  • Ruby uses dynamic typing

What does that mean, exactly?

Typing refers to how variables & method arguments work.

A strongly (or statically) typed language has to declare what types (classes) every variable can accept.

It looks like this:

int n = 1;

Where int is the type, in this case, Integer.

Why is that useful?

Because if you try to assign any other type of object to this variable, the compiler will raise an error & your program won’t even get to run.

This means that you’ll always know what kind of object you’re working with.

With the disadvantage of being less flexible.

In contrast…

Dynamic typing is all about flexibility, variables aren’t tied to a particular type, so the type can change.

Here’s an example:

n = 1
n = "abc"

The downside is that you may run into more errors if your code is sloppy & you don’t get as much when reading code.

That’s one of the major differences!

More in the next section.

Syntax: Simple Things & Boilerplate

Java is the king of boilerplate.

Boilerplate is all that “setup” code that you have to add just to make your code syntactically valid.

As a result…

Java makes SIMPLE things complicated!

Hello World in Java:

class Hello {
  static public void main() {
    System.out.println("Hello World");
  }
}

Then you have to compile this into a class file & run it.

Two steps!

(IDEs help with this.)

Another difference is that expressions in Java end with a semicolon, which is not required in Ruby. You can also leave out parenthesis in Ruby, most of the time.

Hello World in Ruby:

puts "Hello World"

Yep.

That’s it.

It seems like Ruby results in cleaner code. Agree?

On top of that…

You can run this code with a single command from a terminal!

No compilation step needed.

Playing With Code: Built-In REPL

Ruby comes with irb, which makes testing out a bit of code really quick.

You don’t even need to save a file.

Or open an editor!

IRB Example

Java doesn’t have this built-in, at least it doesn’t until Java 9.

File Names & File Organization

Java forces a specific file naming structure & organization.

For example:

If you have a (public) class named Hello, the file name MUST be Hello.java.

This isn’t the case in Ruby.

Also, we don’t have the concept of a private class in Ruby.

Exception Handling

Java has two types of exceptions:

  • Checked exception
  • Unchecked exception

The difference?

You HAVE to handle checked exceptions!

Or your program won’t even run.

Now:

Ruby has only one type of exception.

You can handle it if you want, the interpreter won’t complain about it, but it may end up crashing your program.

Compiler & Language Licensing

Lastly, let’s talk about licensing.

This isn’t usually a problem with programming languages.

Why?

Because they’re open source, with one person as the head maintainer & designer.

Java is different here.

It to a big corporation (Oracle) & that has implications on it’s licensing.

In fact:

There are two versions of the Java runtime, “Oracle JDK”, which (if I understand correctly) starting with version 9 is a commercial product.

Then you have “Open JDK”, which also belongs to Oracle.

But it has an open-source license.

Library & Code Distribution

Another MAJOR difference, one of my favorites (also Matz’s favorite) about Ruby is RubyGems.

It makes distributing libraries (like HTTP clients) much easier.

Because:

  • There is a central repository
  • It’s integrated into the language
  • Many open-source gems are available & easy to find

As far as I know, Java doesn’t have anything close to this, so this is a major win for Ruby.

Summary

You’ve learned about the major difference between Java & Ruby. Including things like static typing, boilerplate, and file naming.

Now you’re better prepared to understand Ruby so you can make the correct decision for you.

Thanks for reading! 🙂

Ruby Yield Yield_Self Featured Image

Understanding Yield & Yield_Self in Ruby (Complete Guide)

What does the word “yield” mean in Ruby? And what does it do exactly?

Well…

Yield is a keyword (meaning it’s a core part of the language) & it’s used inside methods for calling a block.

Here’s what you need to know:

  • Calling a block runs the code inside that block (like calling a method)
  • Yield can pass any number of arguments to the block
  • The block’s return value becomes the return value for yield

You have to understand blocks for this to make sense.

You can think of blocks as methods without names that can be passed as extra arguments to other methods.

Here’s an example:

def make_salad
  yield "lettuce"
  yield "carrots"
  yield "olive oil"
end

make_salad { |ingredient| puts "Adding #{ingredient} to salad!" }

This calls the block 3 times, producing this output:

Adding lettuce to salad!
Adding carrots to salad!
Adding olive oil to salad!

That’s in essence what yield does, is like calling a method, but instead you’re calling the block.

We don’t have a name for the block, so this keyword takes care of that.

Now:

Let’s explore what happens if you don’t have a block to call.

Yield Without a Block == Error Message

If you call yield without having a block, then you get an error.

Example:

def write_code
  yield
end

write_code

# LocalJumpError: no block given (yield)

This error is crystal-clear, “no block given” means that the method call write_code is not providing a block.

How can you prevent this error?

Like this:

def write_code
  yield if block_given?
end

The block_given? method checks if a block is available & this allows you to only yield if that’s true.

Why Use Yield?

Using yield enables blocks.

We use blocks to pass in bits of code as part of a method call.

That’s helpful when:

  • You want to write a generic logging function, that logs how long a bit of code takes to run
  • You want to run some code when the method is done (like “callbacks” in Javascript)
  • You want “lazy code”, code that only runs when needed & that can be customized by the user (for an example of this, read about the Hash#fetch method)

Nice!

Yield_Self – What’s The Difference?

You may find this new yield_self method & think it’s related to yield.

Well, it isn’t.

Even yield(self) is different, because self refers to the current object.

Where yield_self, which was was added in Ruby 2.5, refers to the object we’re calling the method on.

A good use for this method?

Use it whenever you want to chain methods & do something with the object you’re calling yield_self on.

While returning the results, instead of the original object.

Example:

n_squared = ->(n) { n ** 2 }

2
.yield_self(&n_squared)
.yield_self(&n_squared)

# 16

In Ruby 2.6, there is an alias for yield_self, the then method.

But don’t confuse it with your regular yield.

Ok?

Yield in Rails

I should also give a quick mention to the use of yield in Rails & templating engines.

You’ll find yield inside layouts.

Rails replaces it with the contents of the view you’re rendering.

No yield equals empty layout!

That’s how the layout & your views are combined together.

Summary

You have learned about the yield keyword in Ruby! Exactly what it is, how it works & why it matters.

Now give it a try in your Ruby code.

Thanks for reading! 🙂

Ruby 2.7 New Features

New Features, Methods & Improvements in Ruby 2.7

Ruby never stops improving!

Version 2.7 is around the corner with new features & methods. It’s scheduled for release on December 25, 2019.

Now, according to Matz…

This is the last 2.x version release. Because next year we’re getting Ruby 3.0!

But before we get there…

Let’s take a look at some of the changes & new features in 2.7, so you can be ready for the version update.

Enumerable#tally

This is a new Ruby method that counts all the elements in an array & returns a hash with their counts.

You can do this yourself, but this tally method saves you work.

Here’s an example:

%w(a a a b b c).tally

Which results in:

{"a"=>3, "b"=>2, "c"=>1}

I like it!

Numbered Parameters For Blocks [Experimental]

An interesting new feature, which I’ve been wanting for a while, is a default name for block parameters.

Here’s a regular block, with one parameter:

[1,2,3].each { |n| puts n }

This |n| is the parameter, which you have to define to use it.

But what if we had a default name?

Well, that’s one of the goodies that Ruby 2.7 brings with it, although as an experimental feature, it can save us a lot of typing.

Here’s what it looks like:

[1,2,3].each { puts _1 }

Where _1 refers to the first parameter, you can use _2 if you have a 2nd one, and yes, _3 for a 3rd parameter, etc.

Pretty cool!

Now, a little bit of trivia.

This feature was first proposed to look like @1, but that looks too much like an instance variable, so after some discussion, it was settled on using _1 instead.

Array#intersection

New method, but no new functionality.

Actually…

This is more like an alias!

Ruby 2.6 introduced Array union & difference methods, to match the more succinct equivalents of Array#|, and Array#-.

But the missing operation was intersection, which has another hard to remember short version.

The Array#& method.

Now:

What do these methods do & how do they work?

Example:

[1, 2, 3].intersection([2, 3, 4])
# [2, 3]

[1, 2, 3] & [2, 3, 4]
# [2, 3]

Well…

The name kind of gives it away, intersection finds the intersection between two arrays. In other words, it finds which elements are in common.

Short Version Long Version
& intersection
| union
difference

I always forget which one of these 3 methods does what!

But with these new methods, it’s a lot easier to remember because their names mean something.

That’s a good lesson in writing good code, btw.

Enumerable#filter_map

This filter_map method is an attempt to combine the select & map methods into one.

Why?

Because it’s a common operation to filter a list first, then map the remaining elements.

You can do this in two ways:

(1..8).select(&:even?).map { |n| n ** 2 }

# OR

(1..8).map { |n| n ** 2 if n.even? }.compact

I’ve used both, but I tend to lean into the first because the intention is more clear.

Now:

In Ruby 2.7, this filter_map method does this in one pass.

Like this:

(1..8).filter_map { |n| n ** 2 if n.even? }
# [4, 16, 36, 64]

I’m not the biggest fan of having if statements inside blocks, but sometimes they’re needed to get the job done.

Besides that, there is something you should know.

The filter_map operation doesn’t behave like map + compact, because it removes false objects, and compact doesn’t.

A good thing to keep in mind!

Enumerator#produce

Here’s another new method you may find interesting, but it may require some creativity to get the most out of it.

It’s the Enumerator#produce method.

What does it do?

According to the feature proposal:

“This method produces an infinite sequence where each next element is calculated by applying the block to the previous element.”

Yep.

Another way to create never-ending sequences!

Here’s an example:

Enumerator.produce(1, &:next).take(5)
# [1, 2, 3, 4, 5]

In this example, it doesn’t matter if you do take(10) or take(10_000), you’ll get an infinite number of values from it.

Btw, 1 is the initial value.

And &:next is the method called on that value to produce the next element in the sequence.

IRB Gets a Face Lift?

Lately, IRB has been getting some love & attention, and Ruby 2.7 keeps adding to that.

We’re getting:

  • Multi-line editing
  • Syntax Highlighting
  • Built-in RDoc integration
  • Command history enabled by default
  • Auto-completion enabled by default

In fact:

This is such a BIG change that you get a warning when you start up irb with Ruby 2.7.

If you wish to keep using the old version of irb you still can, with the irb --legacy command. My main issue with this new IRB is line editing, in legacy IRB (or in Pry) I can hold ALT & press left arrow to move faster, but this doesn’t work in the new IRB.

Give it a try & see how it works for you.

Ruby Pattern Matching [Experimental]

An often-requested feature that’s coming in 2.7 is pattern matching.

It’s marked as experimental.

But what is pattern matching & how does it benefit you?

Well, if I understand this correctly, pattern matching is like regular expressions, but for data structures (Array/Hash).

Here’s an example:

[1,2,3] in [a,b,c] # true
[1,2,3] in [a]     # false

If there is a match, these variable names (like a) become local variables you can access.

Example with a hash:

{ a: 1, b: 2, c: [] } in { a: a, b: b, c: [] }
# true

p a
# 1

This uses the in keyword.

It’s not new, but uncommon because before Ruby 2.7 in was only used as part of a for loop (highly discouraged in Ruby), so we get to reuse this keyword for something useful.

Even better

It doesn’t matter what variables you use, a,b,c here works, but f,g,h also works.

It’s all about the pattern!

Other Changes

A few extra changes worth mentioning.

  • New compaction GC improves memory fragmentation
  • Method argument **nil now declares that a method takes no keywords
  • Method argument ... adds an argument forwarding mechanism (parenthesis required, like make_salad(...))
  • Fiber improvements. A new pool of fiber objects (from which new fibers are allocated) makes fibers more efficient
  • Thread improvements. A better, more optimized way of creating threads makes multi-threading faster

What do you think about these?

The NEWS file for 2.7 mentions a 10x performance improvement for both fiber & thread creation, I haven’t tested this myself, but if you do let me know about your results.

Summary

You’re now up to date with the latest changes to the Ruby programming language! You learned about IRB changes, new methods & a few experimental features like pattern matching.

Please share this article to spread the news!

Thanks for reading 🙂

1 2 3 40