Today's post is about Arrays and Indexers in JRuby. Here below you will find a very easy to follow program, that demonstrate arrays and indexer, by implementing some simple tasks that will make you grasp the idea of those 2 features real quick. The main goal of this post, is not really teaching arrays because, come on, you probably already know "all" about them, in fact, it is more to show you how you do that in JRuby, in this case, compared to all other 22 languages on future posts, which essentially, is the real aim behind this blog.
This is the first post on this series on a language targeting the JVM. Besides the fact that I had the code from a previous post written in (Iron)Ruby, the newly released version of the (J)Ruby plugin for NetBeans IDE (http://plugins.netbeans.org/plugin/38549/?show=true) helped me decide what to publish next.
By the way, if you missed my most recent post, "New Series - Arrays and Indexers", check it out. It has more details about the following program, and a bunch of definitions for the concepts used on this, and the following, posts.
I encourage you to copy the code below and try it yourself, normally, all programs you find in this blog are source code complete, just paste it on your IDE and run it.
There is room for improvement of the code, using generics is one example, but Generics, Collections, lambdas, etc. will have their own "series" of posts.
require "java"
# Console Program
def main()
# Single-dimensional Array(s)
print_title("Reverse Array Elements")
# Declare and Initialize Array of Chars
letters = Array.new(5," ")
letters[0] = "A"
letters[1] = "E"
letters[2] = "I"
letters[3] = "O"
letters[4] = "U"
print_array(letters)
inverse_letters = reverse_char(letters)
print_array(inverse_letters)
print_title("Sort Integer Array Elements")
# Declare and Initialize Array of Integers
numbers = [10, 8, 3, 1, 5]
print_array(numbers)
ordered_numbers = bubblesort(numbers)
print_array(ordered_numbers)
print_title("Sort String Array Elements")
# Declare and Initialize and Array of Strings
#names = Array.new(5, ["Damian","Rogelio","Carlos","Luis","Daniel"])
# or just
names = ["Damian",
"Rogelio",
"Carlos",
"Luis",
"Daniel"]
print_array(names)
ordered_names = bubblesort(names)
print_array(ordered_names)
# Multi-dimensional Array (Matrix row,column)
print_title("Transpose Matrix")
# for an empty table initialized to 0s
# matrix = Array.new(rows,0) { Array.new(cols,0) }
matrix = [[6, 4, 24],
[1, -9, 8]]
print_matrix(matrix)
transposed_matrix = transpose_matrix(matrix)
print_matrix(transposed_matrix)
# Jagged Array (Array-of-Arrays)
print_title("Upper Case Random Array & Graph Number of Elements")
=begin
# Creating an array of string arrays using the String.Split method
# instead of initializing it manually as follows:
#
# text = [
# [ ["word1", "word2, "wordN"],
# [ ["word1", "word2, "wordN"],
# ...
# ]
#
# Text extract from: "El ingenioso hidalgo don Quijote de la Mancha"
=end
text = [
"Hoy es el dia mas hermoso de nuestra vida, querido Sancho;".split(" "),
"los obstaculos mas grandes, nuestras propias indecisiones;".split(" "),
"nuestro enemigo mas fuerte, miedo al poderoso y nosotros mismos;".split(" "),
"la cosa mas facil, equivocarnos;".split(" "),
"la mas destructiva, la mentira y el egoismo;".split(" "),
"la peor derrota, el desaliento;".split(" "),
"los defectos mas peligrosos, la soberbia y el rencor;".split(" "),
"las sensaciones mas gratas, la buena conciencia...".split(" ")
]
print_jagged_array(text)
uppercase_random_array(text)
print_jagged_array(text)
graph_jagged_array(text)
# Array Exceptions
print_title('Common Array Exceptions')
print_common_array_exceptions(nil)
print_common_array_exceptions(text)
# Accessing Class Array Elements through Indexer
print_title('Alphabets')
vowels = Alphabet.new(5)
vowels[0] = "a"
vowels[1] = "e"
vowels[2] = "i"
vowels[3] = "o"
vowels[4] = "u"
puts "\nVowels={%s}" % [vowels[0],vowels[1],vowels[2],vowels[3],vowels[4]].join(",")
en = Alphabet.new("abcdefghijklmnopqrstuvwxyz")
puts "English Alphabet = {%s}" % [en]
puts "Alphabet Extract en[9..19] = {%s}" % [Alphabet.new(en.slice(9, 10))]
word1 = [en[6],en[14],en[14],en[3]].join("")
word2 = [en[1],en[24],en[4]].join("")
word3 = [en[4],en[21],en[4],en[17],en[24],en[14],en[13],en[4]].join("")
puts "\n%s %s, %s!\n" % [word1, word2, word3]
gets
end
def reverse_char(arr)
arr.reverse
end
def bubblesort(arr)
for i in arr.reverse
for j in (0..arr.count-2)
if arr[j] > arr[j + 1]
swap = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = swap
end
end
end
arr
end
def transpose_matrix(m)
=begin
# Transposing a Matrix 2,3
#
# A = [6 4 24]T [ 6 1]
# [1 -9 8] [ 4 -9]
# [24 8]
=end
transposed = Array.new(m[0].size) { Array.new(m.size) }
for i in 0..(m.size-1)
for j in 0..(m[0].size-1)
transposed[j][i] = m[i][j]
end
end
transposed
end
def uppercase_random_array(arr)
r = java.util.Random.new()
i = r.nextInt(arr.size)
for j in 0..(arr[i].size-1)
arr[i][j] = arr[i][j].upcase
end
end
def print_array(arr)
puts "\nPrint Array Content #{arr.class.name}[#{arr.size}]"
for i in 0..(arr.size-1)
puts " array [%2s] = %2s" % [i, arr[i]]
end
end
def print_matrix(m)
puts "\nPrint Array Content #{m.class.name}[#{m.size}][#{m[0].size}]"
for i in 0..(m.size-1)
for j in 0..(m[0].size-1)
puts " array [%2s,%2s] = %2s" % [i, j, m[i][j]]
end
end
m
end
def graph_jagged_array(arr)
=begin
# When using Arrays, we can use for(each) instead of for by index
# for s in arr
# for w in s
# end
# end
=end
puts "\nPrint Text Content #{arr.class.name}"
for i in 0..(arr.size-1)
line = ""
line += "Line %2s|" % (i+1).to_s
for j in 0..(arr[i].size-1)
line += " * "
end
line += "(#{arr[i].size})"
puts line
end
end
def print_jagged_array(arr)
puts "\nPrint Jagged Array Content #{arr.class.name}"
for i in 0..(arr.size-1)
line = ""
for j in 0..(arr[i].size-1)
line += " " + arr[i][j]
end
if line == line.upcase
line += " <-- [UPPERCASED]"
end
puts line
end
end
def print_common_array_exceptions(arr)
begin
arr.fetch(100)
rescue Exception => ex
puts "\nException: \n%s\n%s" % [ex.class.name, ex.message]
#else
# others
end
end
def print_title(message)
puts ""
puts ("=" * 54)
puts message
puts ("=" * 54)
end
class Alphabet
# Array Field
@letters = []
# Indexer Get/Set Property
def [](idx)
@letters[idx]
end
def []=(idx, value)
@letters[idx] = value.upcase
end
# Read-Only Getter
def length
@letters.size
end
# Constructor/Initializer
def initialize(param)
if param.class == 1.class
@letters = Array.new(param, " ")
elsif param.class == "".class
@letters = param.upcase.chars.to_a
elsif param.class == [].class
@letters = param
else
@letters = nil
end
end
# Overridden Method
def to_s
@letters.join(",")
end
# Method
def slice(start, length)
@letters[start..start+length-1]
end
end
main
The output:
VoilĂ , that's it. Next post in the following days.
