Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

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

Posted on • Edited on • Originally published ateric-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.

# Badname=Mike# Will throw an error# Goodname='Mike'# Goodname="Mike"
Enter fullscreen modeExit fullscreen mode

Number can also be represent as string

text_age="45"number_age=45
Enter fullscreen modeExit 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'putsmessage# Hello World
Enter fullscreen modeExit fullscreen mode

Attention. You cannot add string and number

age=25name='Mike'message=name+' is '+age+' years old'putsmessage# ERROR
Enter fullscreen modeExit 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'putsmessage# Mike is 25 years old
Enter fullscreen modeExit 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 modeExit 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=45message="Your age in 2 years will be#{age+2}"# Your age in 2 years will be 47
Enter fullscreen modeExit 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 modeExit 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'putsname.upcase# MIKE
Enter fullscreen modeExit 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# MIKEputs'Mike'.downcase# mikeputs'mike'.capitalize# Mikeputs'Mike'.reverse# ekiMname='Mike Taylor'putsname.length# 11name=''putsname.empty?# truename='Mike'putsname.include?'ke'# true
Enter fullscreen modeExit 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'putsmessage.sub'blue','red'# The sky is red
Enter fullscreen modeExit fullscreen mode

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

# Validputsmessage.sub'blue','red'# Also validputsmessage.sub('blue','red')
Enter fullscreen modeExit 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'putsmessage.gsub'blue','red'# The sky is red and the car is also red
Enter fullscreen modeExit fullscreen mode

Strip method

Remove white space before or after a string

puts'  Welcome to Ruby World  '.strip# 'Welcome to Ruby World'
Enter fullscreen modeExit fullscreen mode

Chaining methods

It is possible to chain string methods

name='   Mike Taylor 'putsname.sub('Mike','Paul').strip.downcase# paul taylor# In that specific situation, using the parentheses make the code easier to read
Enter fullscreen modeExit 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: _MikeEnter user password: _secretThe user name is Mike and his password is s*cr*t
Enter fullscreen modeExit fullscreen mode

Solution

print'Enter user name: 'name=gets.chompprint'Enter user password: 'password=gets.chomp.strip.downcaseputs"The user name is#{name} and his password is#{password.gsub('e','*')}"
Enter fullscreen modeExit 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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Businessman and blogger #Javascript, #Python and #PHP. My favorite frameworks/librairies are #React, #Laravel, and #Django. I am also a fan of #TailwindCSS
  • Location
    Canada
  • Joined

More fromEric The Coder

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp