Quick introduction to Ring
Ring is small and quick to learn. This page shows everything you need to read the rest of this documentation — values, lists, decisions, functions, classes, errors and files — with programs you can run. No .NET yet.
Who this page is for#
This is an appendix: the rest of the documentation does not depend on reading it in order. If you already write Ring, go back to Getting started. If you come from C#, Python, JavaScript or another language, read this page once: Ring differs from some languages in a few ways, and knowing them helps when you read Ring code and the messages that come from .NET. The five programs are in samples/UsingDotNet/tutorials (ring_basics.ring … ring_errors_files.ring); run one with:
ring ring_basics.ringThis is a quick tour, not the manual. The Ring language documentation (<https://ring-lang.github.io/doc1.28/>) explains everything in depth.
Syntax styles. Ring allows more than one syntax style for the same program. This documentation uses one of them, the first style: blocks are closed with words (ok, next, end, off) and statements are written one to a line. Ring also allows braces { } for control structures (if, for, while, switch) and for functions; a program written with braces runs the same way, and you can use the style you prefer in your own programs.
1. Values, text and numbers#
# Ring in 15 minutes, part 1: values, text, numbers and comparisons (no .NET here: plain Ring)
# 1. A variable needs no declaration and no type; the type belongs to the value. "?" prints a line.
nCount = 3 # a number
cName = "Ring" # a text
lReady = True # a yes/no value: True is 1, False is 0
? nCount
? cName
? lReady
? type(nCount) + " " + type(cName) + " " + type(lReady)
# 2. All numbers are doubles. Whole numbers print without decimals, others with at most a few.
? 7 / 2
? 7 % 2 # the remainder
? floor(7 / 2) # the whole part
? 2 ** 10 # power ("^" is a bit operation in Ring)
? 0.1 + 0.2 = 0.3 # 0 (false): binary fractions are inexact
# 3. Text: "+" joins texts. The LEFT side decides: a text on the left joins ("Count: " + 3 is "Count: 3"),
# a number on the left adds, and then the text must look like a number.
cLine = "Count: " + nCount
? cLine
? "3" + 4 # joins: 34
? 5 + "5" # adds: 10
try
? nCount + " items" # a number on the left: " items" is not a number
catch
? "error: " + substr(cCatchError,15) # the message without the "Error (R41) : " in front
done
? string(nCount) + " items" # string() makes the number a text first
# 4. Text is a list of bytes: indexes start at 1, len() counts bytes
cWord = "Hello, Ring!"
? len(cWord)
? cWord[1] # the first letter
? left(cWord,5) + "|" + right(cWord,5)
? substr(cWord,8,4) # 4 letters from position 8
? upper(cWord) + " " + lower(cWord)
? substr(cWord,"Ring") # the position of a text inside a text (0: not found)
? substr(cWord,"Ring","World") # replace
? trim(" padded ") + "|"
# 5. "=" compares as well as assigns (the context decides); "!=" is different; and / or / not combine tests
? 3 = 3
? "abc" = "ABC" # texts are compared by bytes
? 3 != 4
? (3 > 2) and (not (1 > 2))
? nl + "the end" # nl is a new line3
Ring
1
NUMBER STRING NUMBER
3.50
1
3
1024
0
Count: 3
34
10
error: Invalid numeric string
3 items
12
H
Hello|Ring!
Ring
HELLO, RING! hello, ring!
8
Hello, World!
padded|
1
0
1
1
the endWhat to remember:
- No declarations. A variable gets its type from the value. A name's first letter is a naming convention (
nnumber,ctext,alist,oobject,lyes/no); this documentation uses it. - All numbers are doubles.
7 / 2is3.5(printed as3.50), and a number is exact only up to 2⁵³ (the tutorial Number systems and big numbers). +follows its left side."Count: " + 3joins,5 + "5"adds, and3 + " items"is an error. Usestring(n)when in doubt.- Indexes start at 1, also for text.
len()counts bytes (the tutorial Unicode and encodings). ^is a bit operation; power is**orpow().- Comparing text:
=and!=compare text exactly ("Abc"and"abc"are different);<and>compare numbers, so for the order of two texts usestrcmp(a, b)(less than 0, 0 or more than 0). - A text that looks like a number is still a text:
isNumber("12")is false.0 + "12"converts it to 12 and raises an error when the text is not a number (usetryandcatch). - Names are not case sensitive, keywords included:
cAllis the keywordcallandoRisor, so a variable or a function is not given such a name. TrueandFalseare1and0.
2. Lists#
# Ring in 15 minutes, part 2: lists (the only collection), pairs, nested lists
# 1. A list holds anything. Indexes start at 1. "+" adds an item at the end.
aNames = ["Ann","Bob","Cy"]
aNames + "Dee"
? len(aNames)
? aNames[1] + " " + aNames[len(aNames)]
aNames[2] = "Rob" # change an item
? aNames
# 2. Walk a list with for ... in. The item is a copy: change the list by index.
for cName in aNames
? "hello " + cName
next
for nIndex = 1 to len(aNames)
aNames[nIndex] = upper(aNames[nIndex])
next
? aNames
# 3. Search, insert, delete, sort
? find(aNames,"CY") # the position (0: not found)
insert(aNames,0,"First") # insert after position 0 = at the start
del(aNames,2) # delete the item at position 2
? aNames
aNumbers = [30,5,12,8]
? sort(aNumbers) # sort() gives a NEW sorted list; aNumbers itself does not change
? aNumbers[1]
? sort(["pear","apple","fig"])
# 4. A list of [name, value] pairs is Ring's dictionary: a text key reads the value. :name is the text "name".
aPerson = [ :name = "Ann", :age = 31, :city = "Cairo" ]
? aPerson[:name]
? aPerson[:age] + 1
aPerson[:age] = 32
aPerson[:email] = "ann@example.com" # a new key is added
? len(aPerson)
for aPair in aPerson
? aPair[1] + " = " + aPair[2]
next
? aPerson[:phone] # a key that is not there reads as "" (it does not raise an error)
# 5. Lists inside lists: a table. aTable[row][column]
aTable = [ ["Ann",31], ["Bob",25], ["Cy",40] ]
? aTable[2][1] + " is " + aTable[2][2]
aTable + ["Dee",19]
nTotal = 0
for aRow in aTable
nTotal += aRow[2]
next
? "total age: " + nTotal
# 6. A list assigned to another variable is COPIED. A list passed to a function is the same list: the function changes the original.
aCopy = aNumbers
aCopy[1] = 999
? aNumbers[1] # still 30
addOne(aNumbers)
? aNumbers[1] # 31: the function worked on the original
func addOne aList
aList[1] = aList[1] + 14
Ann Dee
Ann
Rob
Cy
Dee
hello Ann
hello Rob
hello Cy
hello Dee
ANN
ROB
CY
DEE
3
First
ROB
CY
DEE
5
8
12
30
30
apple
fig
pear
Ann
32
4
name = Ann
age = 32
city = Cairo
email = ann@example.com
Bob is 25
total age: 115
30
31A list is the only collection. It can hold numbers, texts, lists and objects. A list of [name, value] pairs is a dictionary; :name is just the text "name", and aPerson[:name] reads a value by key. This pair form is how this package passes named arguments to .NET: [ :server = "x", :port = 80 ] (Core concepts).
Assigning a list or an object copies it, and [oObject, "text"] puts a copy of the object into the new list. A list passed to a function is not copied: the function works on the original.
3. Decisions, loops, functions#
# Ring in 15 minutes, part 3: decisions, loops and functions
# Ring runs a file from the top. If the file has a function called main, Ring calls it by itself when it reaches the end of the file.
# The code at the top level (before the first func) runs first. A func continues until the next func or class, so statements go BEFORE the functions.
nTotal = 0 # a global variable: defined at the top, outside every function
func main
# 1. if / but (else if) / else, closed with ok
nAge = 17
if nAge >= 18
? "adult"
but nAge >= 13
? "teenager"
else
? "child"
ok
# 2. for counts; "step" changes the size of the step. while repeats while the test is true. loop = next round, exit = leave.
for nI = 1 to 5
if nI = 2 loop ok # skip 2
if nI = 5 exit ok # stop at 5
? "for " + nI
next
for nI = 10 to 1 step -4
? "down " + nI
next
nN = 1
while nN < 100
nN *= 3
end
? "while: " + nN
# 3. switch compares one value with several cases
cColor = "green"
switch cColor
on "red"
? "stop"
on "green"
? "go"
other
? "wait"
off
# 4. Functions: parameters come after the name, "return" gives a value (a function without it gives "")
? square(7)
? greet("Ann","Hello")
? greet("Bob","Hi")
aStats = minMax([4,9,2,7]) # return a list to give several values
? "min " + aStats[1] + ", max " + aStats[2]
# 5. A variable made inside a function is local. A variable of the top level (nTotal) is global: functions can read and change it.
addToTotal(5)
addToTotal(6)
? "total (global) = " + nTotal
func square nNumber
return nNumber * nNumber
# A function has one parameter list: calling greet("Ann") with one value raises an error ("less number of parameters").
func greet cName, cGreeting
return cGreeting + ", " + cName
func minMax aList
nMin = aList[1]
nMax = aList[1]
for nItem in aList
if nItem < nMin nMin = nItem ok
if nItem > nMax nMax = nItem ok
next
return [nMin,nMax]
func addToTotal nValue
nTotal += nValueteenager
for 1
for 3
for 4
down 10
down 6
down 2
while: 243
go
49
Hello, Ann
Hi, Bob
min 2, max 9
total (global) = 11- In the style used here, blocks end with a word:
okclosesif,nextclosesfor,endcloseswhile,offclosesswitch.butis else if. (Braces are also allowed, see the note at the top.) - A
funccontinues until the nextfuncorclass, so the code that starts your program goes before the functions, or insidefunc main, which Ring calls by itself at the end of the file. - A Ring function takes the parameters it declares: a call with another number of values raises an error. For overloaded .NET methods, RingDotNet therefore offers the
NULLand named-argument forms (Core concepts). - A variable at the top of the file is global; a variable made in a function is local.
4. Classes and objects#
# Ring in 15 minutes, part 4: classes and objects (the code at the top comes first, the classes go LAST: a func or class continues until the next func or class)
func main
# 1. new makes an object. The parentheses call init().
oAnn = new Person("Ann",31)
? oAnn.name
oAnn.birthday()
? oAnn.describe()
# 2. Attributes are read and written with a dot. An attribute that the class does not have is an error.
oAnn.age = 40
? oAnn.age
# 3. Braces: set attributes (and call methods) of the object inside { }. This is the style of this documentation.
oBob = new Person("Bob",25) {
city = "Oslo"
}
? oBob.describe()
# 4. Inheritance: "from" takes everything of the parent and adds or replaces
oEva = new Student("Eva",20,"Physics")
? oEva.describe()
? oEva.isAdult()
# 5. Objects are COPIED when assigned to another variable: change the copy and the original stays
oCopy = oAnn
oCopy.name = "Copy"
? oAnn.name
# 6. Objects in a list
aPeople = [oAnn,oBob,oEva]
for oPerson in aPeople
? oPerson.name + " " + oPerson.age
next
class Person
name = ""
age = 0
city = "Cairo"
# init runs when the object is made with new Person(...). Give a class an init (even an empty one) if you write new Person()
# with parentheses, and end it with "return self" if the object is used with braces: new Person(...) { ... }
func init cName, nAge
name = cName
age = nAge
return self
func birthday
age++
func describe
return name + " is " + age + " and lives in " + city
func isAdult
return age >= 18
class Student from Person
subject = ""
func init cName, nAge, cSubject
super.init(cName,nAge) # the init of the parent
subject = cSubject
return self
func describe
return super.describe() + ", studies " + subjectAnn
Ann is 32 and lives in Cairo
40
Bob is 25 and lives in Oslo
Eva is 20 and lives in Cairo, studies Physics
1
Ann
Ann 40
Bob 25
Eva 20new Person("Ann",31)makes an object and callsinit. The bracesnew Person(...) { city = "Oslo" }set attributes while the object is made; this is the style used everywhere in this documentation (oForm = new Form() { Text = "Hi" }). The object is used with braces only ifinitends withreturn self.class Student from Personis inheritance;super.init(...)andsuper.describe()call the parent.- Classes are written last in the file: a
funcwritten after a class belongs to that class. - Assigning an object to another variable copies it: change the copy and the original stays.
5. Errors, files and other files#
# Ring in 15 minutes, part 5: errors, files, arguments and other files
func main
# 1. try / catch / done: the error text is in cCatchError. raise() makes an error of your own.
try
nResult = 10 / 0
catch
? "caught: " + substr(cCatchError,14) # a runtime error starts with "Error (R1) : ", then the text
done
try
checkAge(-5)
catch
? "caught: " + cCatchError
done
checkAge(30)
? "30 is fine"
# 2. Files: write() and read() work with the whole text of a file; fexists() asks if it exists
cFile = "ring_intro_demo.txt"
write(cFile,"line one" + nl + "line two" + nl)
? fexists(cFile)
cText = read(cFile)
? string(len(cText)) + " bytes"
aLines = str2list(cText) # a text with lines becomes a list of lines
? string(len(aLines)) + " lines, the second is: " + aLines[2]
remove(cFile)
? fexists(cFile)
# 3. The arguments of the program: sysargv is [the ring program, your file, the arguments ...]
? len(sysargv) >= 2 # true: at least [ring, the file]
# 4. eval() runs text as Ring code; the function name in a text can be called with call
eval("? 6 * 7")
cFunction = "hello"
call cFunction()
# 5. load "file.ring" runs another file first, at the top of your program (see the next page: load "dotnet.ring")
? "done"
func checkAge nAge
if nAge < 0
raise("an age can not be negative: " + nAge)
ok
func hello
? "hello from a function called by name"caught: Can't divide by zero
caught: an age can not be negative: -5
30 is fine
1
18 bytes
2 lines, the second is: line two
0
1
42
hello from a function called by name
donetry … catch … donecatches errors; the message is incCatchError.raise("text")makes an error. This is how every .NET exception arrives in Ring (the tutorial When things go wrong).load "file.ring"runs another file. The first line of every RingDotNet program isload "dotnet.ring".sysargvholds the command line (the tutorial A command-line tool).
Ring and other languages#
Some differences from other popular languages, as facts:
| Often in other languages | In Ring |
|---|---|
| declarations, types | none: the value has the type |
== to compare | = (the context decides); != for different |
| arrays from 0 | lists from 1 |
| integers and decimals | one number type, a double |
"a" + 1 and 1 + "a" the same | the left side decides |
| methods overloaded by parameters | one function per name, with a fixed number of parameters |
{ } blocks | words in the first style (ok, next, end, off, done); braces are allowed too |
string is characters | text is a sequence of bytes (any byte, usually UTF-8) |
| references to objects | objects and lists are copied on assignment |
| keywords are not case sensitive | or, in, to, on, do... also apply to names that spell them: oR is read as or, so a name like oReader is used instead |
Where to go next#
A Ring program uses .NET with two lines:
load "dotnet.ring"
using { "System" "System.Text" }
oBuilder = new StringBuilder("Hello")
? oBuilder.Append(", Ring!").ToString()Then:
- Getting started: install the package and run the first program.
- Core concepts: how .NET names, overloads, properties and enums look in Ring.
- The tutorial chapter The basics: ten short lessons.
- Rules and limits: the points of Ring that matter when you use .NET.