RingDotNetfor Ring

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:

Shell
ring ring_basics.ring
Note

This is a quick tour, not the manual. The Ring language documentation (<https://ring-lang.github.io/doc1.28/>) explains everything in depth.

Note

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#

samples/UsingDotNet/tutorials/ring_basics.ring
# 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 line
Output
3
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 end

What to remember:

2. Lists#

samples/UsingDotNet/tutorials/ring_lists.ring
# 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] + 1
Output
4
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
31

A 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).

Note

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#

samples/UsingDotNet/tutorials/ring_flow.ring
# 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 += nValue
Output
teenager
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

4. Classes and objects#

samples/UsingDotNet/tutorials/ring_classes.ring
# 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 " + subject
Output
Ann
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 20

5. Errors, files and other files#

samples/UsingDotNet/tutorials/ring_errors_files.ring
# 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"
Output
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
done

Ring and other languages#

Some differences from other popular languages, as facts:

Often in other languagesIn Ring
declarations, typesnone: the value has the type
== to compare= (the context decides); != for different
arrays from 0lists from 1
integers and decimalsone number type, a double
"a" + 1 and 1 + "a" the samethe left side decides
methods overloaded by parametersone function per name, with a fixed number of parameters
{ } blockswords in the first style (ok, next, end, off, done); braces are allowed too
string is characterstext is a sequence of bytes (any byte, usually UTF-8)
references to objectsobjects and lists are copied on assignment
keywords are not case sensitiveor, 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:

Ring
load "dotnet.ring"

using { "System" "System.Text" }

oBuilder = new StringBuilder("Hello")
? oBuilder.Append(", Ring!").ToString()

Then:

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.