DEV Community

loading...
Cover image for Learning ruby - day 2

Learning ruby - day 2

aderayevans
Love drawing and learning languages.
・6 min read

Table of Contents

  1. Introduction
  2. Content
  3. Conclusion

Introduction

Hey guys, welcome to my blog recording my ruby self-taught process

I decided to learn this amazing language while I was trying to solving some ruby challenges to get my tenth badge in HackerRank

At the first day, We have gotten to know Ruby. If you found it a little hard to understand then let me know immediately, otherwise I will keep writing this blog as a learning process recording

Today I will focus on more details what we have learned at the first day


Print output

Print value of variable and type of variable

name = "Ade"
puts "Hello #{name}!"
puts "#{name.class.name}"
Enter fullscreen mode Exit fullscreen mode

As we have discussed at the first day "Everything is Object", so we're now able to know that type of variable is a class name

Output

PS D:\Workplace> ruby hello-world.rb
Hello Ade!
String
Enter fullscreen mode Exit fullscreen mode

Print raw version of an object, use for debugging string.

P is a kernel method

a = " \n"
p a
Enter fullscreen mode Exit fullscreen mode

Output

" \n"
Enter fullscreen mode Exit fullscreen mode

Pretty printting, use for print Hash object

json = {
    "2019":[
       {
          "language":"Ruby",
          "edition":"seventh"
       },
       {
          "language":"Python",
          "edition":"sixth"
       },
       {
          "language":"Oracle",
          "edition":"second"
       }
    ],
    "2020":[
        {
          "language":"C++",
          "edition":"first"
       },
       {
          "language":"Java",
          "edition":"fourth"
       },
       {
          "language":"Mysql",
          "edition":"third"
       }
    ]
}
puts json
puts "----------------------------------------------------"
pp json
Enter fullscreen mode Exit fullscreen mode

Output

{:"2019"=>[{:language=>"Ruby", :edition=>"seventh"}, {:language=>"Python", :edition=>"sixth"}, {:language=>"Oracle", :edition=>"second"}], :"2020"=>[{:language=>"C++", :edition=>"first"}, {:language=>"Java", :edition=>"fourth"}, {:language=>"Mysql", :edition=>"third"}]}
----------------------------------------------------
{:"2019"=>
  [{:language=>"Ruby", :edition=>"seventh"},
   {:language=>"Python", :edition=>"sixth"},
   {:language=>"Oracle", :edition=>"second"}],
 :"2020"=>
  [{:language=>"C++", :edition=>"first"},
   {:language=>"Java", :edition=>"fourth"},
   {:language=>"Mysql", :edition=>"third"}]}
Enter fullscreen mode Exit fullscreen mode

As you can see, it looks pretty as it name


Too much if - use Case instead

if today == "Monday"
    puts "2, 30 July 2021"
elsif today == "Tuesday"
    puts "3, 30 July 2021"
#...
else
    puts "8, 30 July 2021"
end
Enter fullscreen mode Exit fullscreen mode
case today
when "Monday"
    puts "2, 30 July 2021"
when "Tuesday"
    puts "3, 30 July 2021"
#...
else
    puts "8, 30 July 2021"
end
Enter fullscreen mode Exit fullscreen mode

Output

6, 30 July 2021
Enter fullscreen mode Exit fullscreen mode

Playing with array elements

arr = [65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78]
puts "Array: #{arr.inspect}"
puts "Array length = #{arr.length}"
puts "First element: #{arr[0]}"
puts "First element: #{arr.first}"
puts "Last element: #{arr[-1]}"
puts "Last element: #{arr.last}"
puts "Five first elements #{arr.take(5).inspect}"
puts "Ignores five first elements #{arr.drop(5).inspect}"
puts "Element at index 3 #{arr[3]}"
puts "Elements from index 3 to index 7 #{arr[3..7]}"
puts "Elements from index 3 to index 6 #{arr[3...7]}"
puts "8 Elements from index 3 #{arr[3, 8]}"
Enter fullscreen mode Exit fullscreen mode

Output

Array: [65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78]
Array length = 14
First element: 65
First element: 65
Last element: 78
Last element: 78
Five first elements [65, 66, 67, 68, 69]
Ignores five first elements [70, 71, 72, 73, 74, 75, 76, 77, 78]
Element at index 3 68
Elements from index 3 to index 7 [68, 69, 70, 71, 72]
Elements from index 3 to index 6 [68, 69, 70, 71]
8 Elements from index 3 [68, 69, 70, 71, 72, 73, 74, 75]
Enter fullscreen mode Exit fullscreen mode

inspect help puts print all array elements in one line


Add elements to array

At the last blog, we have learned a bunch of ways to delete elements from array, let's look back a little

arr = [65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78]
puts "Array: \t\t\t#{arr.inspect}"
arr.shift
puts "Delete first element: \t#{arr.inspect}"
arr.pop.inspect
puts "Delete last element: \t#{arr.inspect}"
arr.delete_at(2).inspect
puts "Delete at index 2: \t#{arr.inspect}"
Enter fullscreen mode Exit fullscreen mode

Output

Array:                  [65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78]
Delete first element:   [66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78]
Delete last element:    [66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77]
Delete at index 2:      [66, 67, 69, 70, 71, 72, 73, 74, 75, 76, 77]
Enter fullscreen mode Exit fullscreen mode

Now we're learning some ways to add elements to array

arr = [65, 66, 67, 68, 69, 70]
puts "Array: \t\t\t#{arr.inspect}"
arr.unshift(97, 98)
puts "Add at first position: \t#{arr.inspect}"
arr.push(254, 255)
puts "Add at last position: \t#{arr.inspect}"
arr.insert(5, 128, 129)
puts "Add at index 5: \t#{arr.inspect}"
Enter fullscreen mode Exit fullscreen mode

Output

Array:                  [65, 66, 67, 68, 69, 70]
Add at first position:  [97, 98, 65, 66, 67, 68, 69, 70]
Add at last position:   [97, 98, 65, 66, 67, 68, 69, 70, 254, 255]
Add at index 5:         [97, 98, 65, 66, 67, 128, 129, 68, 69, 70, 254, 255]
Enter fullscreen mode Exit fullscreen mode

As you can see we can add more than just one element


Here document

puts 'Starting', '------------', <<HERE, 'Real Ending'
    1. Salad mix.
    2. Strawberries.
    3. Cereal.
    4. Milk.
HERE
Enter fullscreen mode Exit fullscreen mode

Output

Starting
------------
    1. Salad mix.
    2. Strawberries.
    3. Cereal.
    4. Milk.
Real Ending
Enter fullscreen mode Exit fullscreen mode

This will print 'Starting' and '------------' normally as puts always do

The <<HERE here means the next occurrence of HERE will be the end of this document

'Real Ending' is lying right after the <<HERE, will be print out right after the end of the document

You can set multiple << to exchange words in the document

<<HERE will be failed if there is any space or tab before the next occurrence HERE, <<-HERE is saying the next occurence can have some space, tab or HERE

Please check this link to learn more about this feature

https://en.wikibooks.org/wiki/Ruby_Programming/Here_documents


String

In this part, we're going to talk a little more about string in Ruby

String elements can be called in multiple ways

  • Each char
str.each_char {|x| p x}
Enter fullscreen mode Exit fullscreen mode

Output

"W"
"h"
"a"
"t"
"'"
"s"
" "
"u"
"p"
"?"
Enter fullscreen mode Exit fullscreen mode
  • Each byte
str.each_byte {|x| p x}
Enter fullscreen mode Exit fullscreen mode

Output

87
104
97
116
39
115
32
117
112
63
Enter fullscreen mode Exit fullscreen mode
  • Each line
"hello\nworld".each_line {|s| p s}
Enter fullscreen mode Exit fullscreen mode

Output

"hello\n"
"world"
Enter fullscreen mode Exit fullscreen mode

We can access elements of a string just like how we do with array

But we cannot delete or add elements to string like we do with array or hash

This is how we do it

Remember these methods will just return a new string, it does not change the original string

  • Delete last char
str = "Hi   \t\r\n"
p str.chop.chop
Enter fullscreen mode Exit fullscreen mode

Output

"Hi   "
Enter fullscreen mode Exit fullscreen mode

You can see that we can chop multiple time, \r, \n, \r\n (exept \n\r though) will be treat as one char

  • Delete multiple last chars
str = "Hi, My name is Ade\r\n\r"
p str = str.chomp
p str = str.chomp
p str.chomp "Ade"
Enter fullscreen mode Exit fullscreen mode

Output

"Hi, My name is Ade\r\n"
"Hi, My name is Ade"
"Hi, My name is "
Enter fullscreen mode Exit fullscreen mode

Delete \r or \n or \r\n unless there is a parameter

  • Delete whitespaces
str = "   \r\n\tHi     ,  Are you having fun?\t   \r    \n"
p str.strip
Enter fullscreen mode Exit fullscreen mode

Output

"Hi     ,  Are you having fun?"
Enter fullscreen mode Exit fullscreen mode

Delete the leading and trailing \t\n\r and whitespaces

  • Append str
str = ""
str += "Hello"
# or
str = ""
str << "Ruby is " << "pretty"
# How to append non-string
str << 3.14.to_s
Enter fullscreen mode Exit fullscreen mode
  • Add to the beginning
str = "Gimme your wallet"
p str
p str.prepend("Please, ")
Enter fullscreen mode Exit fullscreen mode

Output

"Gimme your wallet"
"Please, Gimme your wallet"
Enter fullscreen mode Exit fullscreen mode

Check text occurs in str with include

str.include? "wallet"
Enter fullscreen mode Exit fullscreen mode

Replace text in str with gsub, first parameter can be RegExp or String, second parameter is string will replace the occurrence texts

str.gsub(/wallet/, heart)
Enter fullscreen mode Exit fullscreen mode
str = "Please, Gimme your wallet"
if str.include? "wallet"
    puts str.gsub(/wallet/, "heart")
end
Enter fullscreen mode Exit fullscreen mode

Output

Please, Gimme your heart
Enter fullscreen mode Exit fullscreen mode

Conclusion

We have learned more about printing object

Interesting feature called Here document to print multiple line strings

Acknowledged how to access, add and delete elements in array and string, or as i say "playing around with array and string"


I'd like to thank HackerRank for giving me a chance to acknowledge and be interesting in this cool language

If guys found Ruby is fascinating, please come to the link below and solve some Ruby challenges with me

https://www.hackerrank.com/domains/ruby

If you have any question or suggestion, please let me know at the comment section below.

OK I'm going to wrap this up here

Thanks for reading my blog

Discussion (0)