export default class $Stdout {
constructor () {
this.putc = putc;
this.puts = puts;
}
}
import { putc } from 'ruby';
Prints a character to stdout. Only prints the first letter of the string and only takes in a single string or number.
putc('ABC');
// A
Prints the character equivalent of the number that is passed in.
putc(65);
// A
Does not print new new lines.
putc('A');
putc('B');
putc('C');
// ABC
Returns the original argument
let word = putc('ABC');
word; // 'ABC'
function putc (arg) {
if (arguments.length !== 1) {
throw `ArgumentError: wrong number of arguments (${arguments.length} for 1)`;
}
if (!(isNumber(arg) || isString(arg))) {
throw `no implicit conversion of ${typeof arg} into Integer (TypeError)`;
}
let output;
if (isString(arg)) {
output = arg.slice(0, 1);
} else {
output = String.fromCharCode(arg);
}
process.stdout.write(output);
return arg;
}
import {puts} from 'ruby';
Prints the string to stdout
puts('this is a test');
// this is a test
Prints the number to stdout
puts(10);
// 10
Prints the boolean to stdout
puts(true);
// true
Prints the regex in the form (?-mix:the_regex)
let regex = /^this is a test$/;
puts(regex);
// (?-mix:^this is a test$)
Prints an empty string to stdout
puts(null);
// ''
puts(undefined);
// ''
Prints the string NaN
puts(NaN);
// NaN
puts(0/0);
// NaN
Prints the string NaN
puts(NaN);
// NaN
puts(0/0);
// NaN
Prints each element to stdout on a new line
puts(['this', 'is', 'a', 'test']);
// this
// is
// a
// test
Prints the string version of objects that inherit directly from the Object prototype
puts({this_is: 'a test'});
// { this_is: 'a test' }
Prints the object’s construtor’s name in the form: #<ClassName>
. Unfortunately, javascript does not expose the memory location of the object, so that can not be added as a reference id to the ouput.
puts(ruby.$stdout);
// #<$Stdout>
Prints the function’s construtor’s name in the form: #<Name>
.
puts(function () { return 'this is a test'});
// #<Function>
If multiple arguments are passed in, they’ll be printed to stdout separated by new lines
puts('this', 'is', 'a', 'test', ruby.$stdout);
// this
// is
// a
// test
// #<$Stdout>
function puts () {
each(arguments, (arg) => {
if (isString(arg) || isNumber(arg) || isBoolean(arg)) {
_printWithNewLine(String(arg));
} else if (isNull(arg) || isUndefined(arg)) {
_printWithNewLine('');
} else if (isRegExp(arg)) {
let stringifiedRegEx = _convertRegexToString(arg);
_printWithNewLine(stringifiedRegEx);
} else if (arg instanceof Error) {
let stringifiedError = _convertErrorToString(arg);
_printWithNewLine(stringifiedError);
} else if (isArray(arg)) {
each(arg, (element) => {
puts(element);
});
} else if (!isPlainObject(arg) && isObject(arg)) {
_printWithNewLine(`#<${arg.constructor.name}>`);
} else {
console.log(arg); // hack to make plain objects print semi-correctly
}
});
}