DEV Community

Cover image for Sharpen your Ruby: Part 2
Eric The Coder
Eric The Coder

Posted on • Updated on • Originally published at eric-the-coder.com

Sharpen your Ruby: Part 2

I develop in Javascript, Python, PHP, and Ruby. By far Ruby is my favorite programming language. Together let start a journey and revisit our Ruby foundations.

Follow me on Twitter: EricTheCoder_

You want to sharpen your Ruby?

In this series, we will start from the beginning and will discover every aspect of Ruby one step at a time.

Each post will include some theory but also exercise and solution.

If you have any questions/comments or your are new and need help, you can comment below or send me a message.

Strings Declaration

String variable represents any text data. A key point for the syntax of strings declaration is that they have to be enclosed in single or double-quotes. The program will throw an error if they are not wrapped inside quotation marks.

# Bad
name = Mike # Will throw an error

# Good
name = 'Mike'

# Good
name = "Mike"
Enter fullscreen mode Exit fullscreen mode

Number can also be represent as string

text_age = "45"
number_age = 45
Enter fullscreen mode Exit fullscreen mode

The variable text_age is a string variable. It cannot be processed in Ruby as a number like be used in addition or multiplication etc.

The number_age variable is an integer number so that variable can be part of any Ruby number manipulations methods.

String concatenation

String can be add together like this

message = 'Hello' + ' ' + 'World'
puts message # Hello World
Enter fullscreen mode Exit fullscreen mode

Attention. You cannot add string and number

age = 25
name = 'Mike'
message = name + ' is ' + age + ' years old'
puts message # ERROR
Enter fullscreen mode Exit fullscreen mode

That code returns an error because Ruby cannot add number to string.

To make this code work, we have to convert the age variable to string using the to_s method

message = name + ' is ' + age.to_s + ' years old'
puts message # Mike is 25 years old
Enter fullscreen mode Exit fullscreen mode

String Interpolation

String interpolation is replacing placeholders with values in a string literal.

For string interpolation to work. String has to be wrapped inside a double quotation mark. Here an example

name = 'Mike'
message = "Hello #{name}" 
# Hello Mike
Enter fullscreen mode Exit fullscreen mode

If the last code snippet, the message variable will be processed by Ruby before assignment. The #{name} placeholder will be replaced by the containing variable value.

Inside placeholder #{} any Ruby expression can be used...

age = 45
message = "Your age in 2 years will be #{age + 2}"
# Your age in 2 years will be 47
Enter fullscreen mode Exit fullscreen mode

In Ruby everything is an object!

You maybe have ear this before. What does that mean for us the developer?

First, what is an object? An object refers to a particular instance of a class with its own methods and properties.

In Ruby types are defined as classes, so for example, if you have a string variable, it's an instance of the String class.

For example, take this variable

message = "Hello World"
Enter fullscreen mode Exit fullscreen mode

This 'message' variable will be dynamically typed by Ruby as a string. That string is a class. So message is an instance of the class string.

In Ruby the String class already has many methods to help do basic and advance string manipulations.

That also means that the 'message' variable will inherit all the methods and properties of his parent class (String).

Example of method call (syntax: object.method)

name = 'Mike'
puts name.upcase
# MIKE
Enter fullscreen mode Exit fullscreen mode

'upcase' is a method of the String class. This method converts all the string characters to uppercase.

For now, if you don't understand all that class instance thing THAT'S NORMAL! We will cover class and object later.

The only thing we need to understand for now is that variables like a string variable have methods we can call to automatically do some stuff.

Here are some string methods available in Ruby.

puts 'Mike'.upcase
# MIKE

puts 'Mike'.downcase
# mike

puts 'mike'.capitalize
# Mike

puts 'Mike'.reverse
# ekiM

name = 'Mike Taylor'
puts name.length
# 11

name = ''
puts name.empty?
# true

name = 'Mike'
puts name.include? 'ke'
# true
Enter fullscreen mode Exit fullscreen mode

Look how those methods names are self-descriptive. We do not need any comments and any explanation to understand what each method does... Welcome to Ruby world!

More String methods

Now that we understand the basics we will start to learn more advanced string methods.

The sub and gsub method

Ruby has a handy string method to replace part of a string.

message = 'The sky is blue'
puts message.sub 'blue', 'red'
# The sky is red
Enter fullscreen mode Exit fullscreen mode

Note the method call has no parentheses to enclose parameters. In Ruby those are optional.

# Valid
puts message.sub 'blue', 'red'

# Also valid
puts message.sub('blue', 'red')
Enter fullscreen mode Exit fullscreen mode

The convention is to omit the parentheses unless the code seems clearer with them.

The sub method replaces the first occurrence. The gsub method replaces all the occurrences.

message = 'The sky is blue and the car is also blue'
puts message.gsub 'blue', 'red'
# The sky is red and the car is also red
Enter fullscreen mode Exit fullscreen mode

Strip method

Remove white space before or after a string

puts '  Welcome to Ruby World  '.strip
# 'Welcome to Ruby World'

Enter fullscreen mode Exit fullscreen mode

Chaining methods

It is possible to chain string methods

name = '   Mike Taylor '
puts name.sub('Mike', 'Paul').strip.downcase
# paul taylor
# In that specific situation, using the parentheses make the code easier to read
Enter fullscreen mode Exit fullscreen mode

Exercise

Create a little program that:

  • Input the user name and store the result in a variable
  • Input the user password and store the result in a variable
  • Remove password before or after white space
  • Convert the password to lowercase
  • Display user name and password but replace the password letter 'e' with a star

Here are the result

Enter user name: _Mike
Enter user password: _secret

The user name is Mike and his password is s*cr*t
Enter fullscreen mode Exit fullscreen mode

Solution

print 'Enter user name: '
name = gets.chomp

print 'Enter user password: '
password = gets.chomp.strip.downcase

puts "The user name is #{name} and his password is #{password.gsub('e', '*')}"
Enter fullscreen mode Exit fullscreen mode

Conclusion

That's it for today. The journey just started, stay tuned for the next post very soon. (later today or tomorrow)

If you have any comments or questions please do so here or send me a message on Twitter.

Follow me on Twitter: EricTheCoder_

Top comments (0)