Introduction to Ruby for absolute beginners: Part two
puts "Hello, World"ruby 2.5.5p157 (2019-03-15 revision 67260) [x86_64-linux]
Hello, World
=> nil
String Basics
Welcome back to part two of this tutorial, the most important take away of this tutorial is to introduce you to basics concept to get you started with Ruby and I will also be sharing resources to you further. On an important note, like so many other skills, becoming a better programmer comes with practice, trying to solve the problem with the new language and read other peoples code to see how they approach the problem they are solving. And you basically learn from patterns and build on your knowledge and become better daily. So let’s dive in.
Strings are a series of characters in order, this is a data type that we most relate with as human it’s the way we communicate like the example Hello World String in our example above. Defining a String data type is as simple as putting the characters double or single quotes. "Hello, World" or 'Hello, World'
both are valid String we will explain the subtle differences down the line.
"Hello, World".class'Hello, World'.class# Both print out=> String
When we ask for the class of bothe we can see that both return a String. You can any data type in Ruby what class they are. We can even ask a data type of what methods they have, methods are actions that can be performed on a data type.
"Hello, World".methods=> [:encode, :include?, :%, :*, :+, :shellescape, :count, :shellsplit, :partition, :to_c, :sum, :next, :casecmp, :casecmp?, :insert, :bytesize, :match, :match?, :succ!, :<=>, :next!, :index, :rindex, :upto, :==, :===, :chr, :=~, :byteslice, :[], :[]=, :scrub!, :getbyte, :replace, :clear, :scrub, :empty?, :eql?, :-@, :downcase, :upcase, :dump, :setbyte, :swapcase, :+@, :capitalize, :capitalize!, :undump, :downcase!, :oct, :swapcase!, :lines, :bytes, :split, :codepoints, :freeze, :inspect, :reverse!, :grapheme_clusters, :reverse, :hex, :scan, :upcase!, :crypt, :ord, :chars, :prepend, :length, :size, :start_with?, :succ, :sub, :intern, :chop, :center, :<<, :concat, :strip, :lstrip, :end_with?, :delete_prefix, :to_str, :to_sym, :gsub!, :rstrip, :gsub, :delete_suffix, :to_s, :to_i, :rjust, :chomp!, :strip!, :lstrip!, :sub!, :chomp, :chop!, :ljust, :tr_s, :delete, :rstrip!, :delete_prefix!, :delete_suffix!, :tr, :squeeze!, :each_line, :to_f, :tr!, :tr_s!, :delete!, :slice, :slice!, :each_byte, :squeeze, :each_codepoint, :each_grapheme_cluster, :valid_encoding?, :ascii_only?, :rpartition, :encoding, :hash, :b, :unicode_normalize!, :unicode_normalized?, :to_r, :force_encoding, :each_char, :unicode_normalize, :encode!, :unpack, :unpack1, :to_json_raw, :to_json_raw_object, :to_json, :<=, :>=, :between?, :<, :>, :clamp, :instance_variable_set, :instance_variable_defined?, :remove_instance_variable, :instance_of?, :kind_of?, :is_a?, :tap, :instance_variable_get, :instance_variables, :method, :public_method, :singleton_method, :define_singleton_method, :public_send, :extend, :to_enum, :enum_for, :pp, :!~, :respond_to?, :object_id, :send, :display, :nil?, :class, :singleton_class, :clone, :dup, :itself, :yield_self, :taint, :tainted?, :untrust, :untaint, :trust, :untrusted?, :methods, :frozen?, :protected_methods, :singleton_methods, :public_methods, :private_methods, :!, :equal?, :instance_eval, :instance_exec, :!=, :__send__, :__id__]# Total numbers of methods."Hello, World".methods.count
=> 188
As we can see from above a String as a total of 188 methods that can be performed on it. # comment
this is the way to provide comment in your Ruby code, the Ruby interpreter will ignore any line that is preceded with an # symbol as a piece of information you are leaving for yourself or other programmers reading your code to understand it better.
puts "I love Ruby"
puts "I will be coding for 7 straight daysputs "------------------"print "Chicken or Egg"
print "I think Eggg"
print "It's Chicken"ruby 2.5.5p157 (2019-03-15 revision 67260) [x86_64-linux]
I love Ruby
I will be coding for 7 straight days
------------------
Chicken or EggI think EgggIt's Chicken=> nil
from the above code snippets if you run it on Repl you will see that both puts and print render a String but in different ways, what do you notice? Print display everything on one line without any space between them while puts each statement on a line of their own.
puts "I love Ruby"
puts "I will be coding for 7 straight days"
puts "------------------"print "Chicken or Egg \n"
print "I think Eggg \n"
print "It's Chicken"ruby 2.5.5p157 (2019-03-15 revision 67260) [x86_64-linux]
I love Ruby
I will be coding for 7 straight days
------------------
Chicken or Egg
I think Eggg
It's Chicken=> nil
Adding \n
to the end of the String with the print, you will see that we achieve the same input as puts, \n
means return a new line.
Let’s perform some String operations from the 188 we have on our arsenal giving to us for free by Ruby, you can even create your own custom methods, how sweet is that.
puts "I love Ruby".upcase
=> I LOVE RUBYputs "I will be coding for 7 straight days".length
=> 36puts "I love Ruby".reverse
=> ybuR evol Iputs "I will be coding for 7 straight days".downcase
=> i will be coding for 7 straight daysputs "I love Ruby".size
11
This is just scratching the surface of so many inbuilt methods in Ruby, so let takes things a little up. We can concatenate Strings together to build a more complex String that’s what we will expect from any good language right.
# Concatenationputs "Hello" + " " + "World"
puts "I love Ruby" + " So Much"# Interploationname = "Peter Ayeni"
age = 14puts "Hello, #{name}"puts "My name is #{name} and I am #{age} years old"# Resultsruby 2.5.5p157 (2019-03-15 revision 67260) [x86_64-linux]
Hello World
I love Ruby So Much
Hello, Peter Ayeni
My name is Peter Ayeni and I am 14 years old
=> nil
From the code above you can see how we can build up more complex strings using Concatenation and Interpolation in Ruby. Key take away here is that you should use double quotes when you are doing interpolation try the interpolated code section with single quotes and see what you get. Thou we have not talked about variable names in Ruby, from the code above you see that we defined two variables name and age. Now we can use the name or age
in any part of our code and they will return to us the values they are set to respectively.
Working with Numbers
puts 3 + 4 # Addputs 4 / 2 # Divisionputs 4 * 2 # Multiplyputs 10 - 2 # Subtractputs 10 % 3 # Modulosputs 10 ** 3 # Exponentruby 2.5.5p157 (2019-03-15 revision 67260) [x86_64-linux]
7
2
8
8
1
1000
=> nil
Ruby allows us to perform operations on numbers we have Integers and Floats Data types in Ruby. And many Maths operations can be performed on these data types.
puts 3.class # Integerputs 2.4.class # Floatruby 2.5.5p157 (2019-03-15 revision 67260) [x86_64-linux]
Integer
Float
=> nil3.methods # Integerruby 2.5.5p157 (2019-03-15 revision 67260) [x86_64-linux]
=> [:-@, :**, :<=>, :upto, :<<, :<=, :>=, :==, :chr, :===, :>>, :[], :%, :&, :inspect, :+, :ord, :-, :/, :*, :size, :succ, :<, :>, :to_int, :coerce, :divmod, :to_s, :to_i, :fdiv, :modulo, :remainder, :abs, :magnitude, :integer?, :numerator, :denominator, :floor, :ceil, :round, :truncate, :lcm, :to_f, :^, :gcdlcm, :odd?, :even?, :allbits?, :anybits?, :nobits?, :downto, :times, :pred, :pow, :bit_length, :digits, :rationalize, :gcd, :to_r, :next, :div, :|, :~, :to_json, :+@, :eql?, :singleton_method_added, :i, :real?, :zero?, :nonzero?, :finite?, :infinite?, :step, :positive?, :negative?, :rectangular, :arg, :real, :imaginary, :imag, :abs2, :angle, :phase, :conjugate, :conj, :to_c, :polar, :clone, :dup, :rect, :quo, :between?, :clamp, :instance_variable_set, :instance_variable_defined?, :remove_instance_variable, :instance_of?, :kind_of?, :is_a?, :tap, :instance_variable_get, :instance_variables, :method, :public_method, :singleton_method, :define_singleton_method, :public_send, :extend, :to_enum, :enum_for, :pp, :=~, :!~, :respond_to?, :freeze, :object_id, :send, :display, :nil?, :hash, :class, :singleton_class, :itself, :yield_self, :taint, :tainted?, :untrust, :untaint, :trust, :untrusted?, :methods, :frozen?, :protected_methods, :singleton_methods, :public_methods, :private_methods, :!, :equal?, :instance_eval, :instance_exec, :!=, :__send__, :__id__]2.4.methods # Floatruby 2.5.5p157 (2019-03-15 revision 67260) [x86_64-linux]
=> [:-@, :**, :<=>, :<=, :>=, :==, :===, :eql?, :%, :*, :inspect, :+, :-, :/, :<, :>, :to_int, :coerce, :divmod, :to_s, :to_i, :fdiv, :modulo, :abs, :magnitude, :to_r, :zero?, :finite?, :numerator, :floor, :ceil, :round, :truncate, :to_f, :positive?, :negative?, :arg, :infinite?, :rationalize, :denominator, :angle, :phase, :hash, :quo, :nan?, :next_float, :prev_float, :to_json, :+@, :singleton_method_added, :i, :remainder, :real?, :integer?, :nonzero?, :step, :rectangular, :real, :imaginary, :imag, :abs2, :conjugate, :conj, :to_c, :polar, :clone, :dup, :rect, :div, :between?, :clamp, :instance_variable_set, :instance_variable_defined?, :remove_instance_variable, :instance_of?, :kind_of?, :is_a?, :tap, :instance_variable_get, :instance_variables, :method, :public_method, :singleton_method, :define_singleton_method, :public_send, :extend, :to_enum, :enum_for, :pp, :=~, :!~, :respond_to?, :freeze, :object_id, :send, :display, :nil?, :class, :singleton_class, :itself, :yield_self, :taint, :tainted?, :untrust, :untaint, :trust, :untrusted?, :methods, :frozen?, :protected_methods, :singleton_methods, :public_methods, :private_methods, :!, :equal?, :instance_eval, :instance_exec, :!=, :__send__, :__id__]
You can see loads of methods available to us for both Integer and Floats Data Types. Take time to play with some of them. There is no point memorising all these methods since you know how to look them up when you need them, just know they exist and Ruby as awesome documentation make them your friends and don’t be afraid to ask Google.
Booleans and Control Flow
puts false
puts truename = "Peter"
puts name.length
=> 5puts name.length > 4
=> trueputs name.length < 5
=> falseputs name.length == 5
=> trueputs name.length >= 5
=> trueputs name.length <= 4
=> false
Booleans data types are simply straight forward true
or false
combine with different comparison operators can be used to make certain decisions on our code.
Control Flow is the way we control and direct our code to do certain operations based on certain conditions. Code run from top to bottom, control flows help us branch out, let see some examples.
name = "Peter"if name == "Peter"
puts "I know you"
else
puts "Can we get to know each other"
endruby 2.5.5p157 (2019-03-15 revision 67260) [x86_64-linux]
I know you
=> nil
We can also use elsif
to handle another level of condition.
name = "James"if name == "Peter"
puts "I know you"
elsif name == "James"
puts "I remember that name"
else
puts "Can we get to know each other"
endruby 2.5.5p157 (2019-03-15 revision 67260) [x86_64-linux]
I remember that name
=> nil
There is also Switch Case that you can use to test multiple cases of a variable you can Google around about Switch Case in Ruby. You can also combine multiple conditional operators, see examples below.
# The Truth table for && also called "and" operatortrue && false
=> false
false && true
=> false
false && false
=> false
true && true
=> true# The Truth table for || also called "or" operatortrue || false
=> true
false || true
=> true
true || true
=> true
false || false
=> false# There are also not operator
!=
!true
=> false
!false
=> true
Methods
We have used internal methods that are built into Ruby, we can also define our own custom methods to do certain custom action in our programme. The rule of thumb is if there is an action that will be carried out throughout your code you can encapsulate them into their own methods.
def checkpassword(password) if password.length < 6
puts "Password is too short"
else
puts "Great"
endend# Call check password with one arguments
checkpassword("mypas") # => Password is too short
checkpassword("mypassword") # => Great
Here we define simple a simple method checkpassword
that does a simple job of checking if the user password is shorter than 6, it takes one argument the password and uses the if statement control flow and comparison operator to check if the argument is shorter than 6 and give the user appropriate feedbacks. This is a simple method, we can write methods that can do more things building on this structure.
This is a lot of information write now just take some time to test out those codes, Google about keywords or concept you don’t understand visit the Ruby documentation and be curious. That’s how we learn and grow as a developer. In part three we will discuss Loop, Array and Hashes in Ruby.
See you then.
Resources
Flatiron School Learn Ruby
Learn Enough Ruby to Be Dangerous by Michael Hartl
Learn Ruby by Code Academy
Ruby Documentation