In previous tutorial of ruby on ubuntu linux, we checked out the installation and few other basic interpreter usage. In this tutorial we are going to cover more concepts like – strings, variables, arrays and hash in ruby.
Let’s first start with the variable. Like any other programming language you use the assignment operator to assign the value. Check the following examples.
var a = 11;
name ="Mahesh";
Now we’ll get into the String manipulation. Note that ruby strings allow plenty of escape sequence for you to make it easy to read the output string.
s1 = "Mahesh";
s2 = "Hello";
puts s2, s1
You can also concatinate the string with + operator. In such case make sure you keep enough distance in between the string for better readability.
String Interpolation
If you wish to embed the result of string operation in between another string. You can use #{ and }. See this example.
s1= "Hey ";
s2= "Mahesh";
s3 = "Welcome to Ruby, #{s1+s2}";
puts s3
String Split and Join
This is fairly easy to do and we’ll see how to use the split and join using the examples.
#! split example
num="one, two, three";
num_a=num.split(/,/)
#! join example
num_a.push("four","five")
num=num_a.join(',')
puts num
Now that we’ve seen some basic strings manipulation. Let’s see how to work with arrays. There are two ways to create an array.
Ruby Array
Method 1: a1=Array.new
Method 2: a2= [] and a2= [“un”, “dos”, “tres”];
If you wish to add more items to arrays. You can use push() method.
e.g.
a2.push("yup")
puts a2
You can also print individual array item using the index number of array.
Ruby Hashes
Hash works similar to the arrays, there are some slight changes in the way you arrange the key and value pair in hashes.
a3=Hash.new
a3[]
You can add the key and value pair in hashes in following way.
a3={:one=>"un",:two=>"dos",:three=>"tress"}
puts a3
That’s all for now. We’ll see some more advanced topic in our next tutorial. Till then you try these examples and see where you get stuck. Your feedback is always appreciated. Feel free to let me know your views in the comments or send me a tweet @maheshkale.