Try Ruby
Reference: http://tryruby.org/
Interactive prompt
To open an interactive prompt on Mac OS X type: irb
Some simple functions
"Jimmy".reverse
to reverse a string
"Jimmy".length
to get the length of a string
"Jimmy" * 5
Conversions
40.to_s.reverse
. You can't reverse a number, but you can if you convert to a string first. Reverse is not defined for numbers. It is defined for arrays.
to_s
converts to stringsto_i
converts to integersto_a
converts to arrays (or lists)
Lists
[]
defines an empty list
[12,47,35].max
to get the maximum number in a list of integers
[12,47,35].sort
to sort them
ticket = [12,47,35]
will assign the list to a variable called ticket
ticket.sort
will output the list sorted, but the value of ticket
remains unchanged
ticket.sort!
will sort the list and reassign it to ticket
Strings
poem["am"] = "was"
will replace the first instance of am
with was
in the string variable poem
poem.lines.to_a.reverse.join
will break a multi-line string into lines, add them to an array, reverse the array, then join the elements of the array back together to once again make a string. to_s
instead of join
would also have worked.
Methods can sometimes use !
exclamation marks, and sometimes ?
question marks.
Hashes
Hashes or dictionaries are created using {} e.g. books = {}
.
This is actually short for Hash.new
.
books.keys
will return a list of all the keys in the hash.
Symbols
Instead of using the same words over and over, create a symbol using :
e.g. :success
.
Blocks
Blocks can be defined starting with an {
and ending with }
.
e.g. books.values.each { |rate| ratings[rate] += 1 }
.
Blocks can alternatively be started with do
and finished with end
.
Files and directories
Dir.entries "/"
gives an array of strings containing the names of all the directories or files in the root directory.
Dir["/*.txt"]
will just list the text files in the root directory. This uses the []
method, similar to entries, but which searches for files using wildcard characters.
File.read("/comics.txt")
will read the contents of the file.
Use FileUtils.cp('/comics.txt', '/Home/comics.txt')
to copy files.
Open a file in append mode using add some lines:
File.open("/Home/comics.txt", "a") do |f|
f << "cat and girl"
end
Date and time
File.mtime("/Home/comics.txt")
to find the last modified time of a file.
Time.now.hour
to give just the hour.
Time.now - 2.weeks
will give you the date 2 weeks ago.
Methods
Start with def
, finish with end
, indent if you like.
def load_comics( path )
comics = {}
File.foreach(path) do |line|
name, url = line.split(': ')
comics[name] = url.strip
end
comics
end
File.foreach
is a method which opens a file and hands each line to the block.
require 'popup'
if you need to import a library called popup
. It will be loaded into the Libraries folder.
Classes
Simple class definition:
class BlogEntry
attr_accessor :title, :time, :fulltext, :mood
end
Add a constructor:
class BlogEntry
def initialize( title, mood, fulltext )
@time = Time.now
@title, @mood, @fulltext = title, mood, fulltext
end
end
Accessors can be used outside the object using normal dot notation e.g. entry.title
.
When inside the object prepend the @
symbol. e.g. @title
.
More on lists
sort_by
can be used on a list of objects to sort them:
e.g. blog.sort_by { |entry| entry.time }
e.g. blog.sort_by { |entry| entry.time }.reverse
map
can be used to replace certain elements in a list
e.g. blog.map {"Bruce Willis"}
will replace each BlogEntry object in the list with a string