PlayMyCode Tips

Here's some tips for PlayMyCode that relate to features not yet available:

So, let's say you have two strings:

myString1 = "123"
myString2 = "45.67"

Currently, there's no defined command to allow you to convert these strings to either integer or floating point values.  However, all is not lost as you can use some fancy bit manipulation for which I've put together two helper functions below:

// Convert the given String to an integer
def toInteger(string)
    return string | 0
end

// Convert the given String to a floating point number
def toFloat(string)
    return string ** 1
end

And here's what happens with our original Strings:

myInteger = toInteger(myString1)
console(myInteger)


123


myFloat = toFloat(myString2)
console(myFloat)


45.67


Thanks to Joe at PlayMyCode for pointing the above out!

Here's some more helper functions I knocked up for use with Strings:

// Returns a new string that is a substring of the given string
def subString(str, startIdx, endIdx)
    val = ""
    startIdx.upTo(endIdx) do |i|
        c = str.getChar(i)
        val = val + c
    end
    return val
end

// Tokenize the given string and return entries in a block
def tokenize(str, token)
    val = ""
    str.each() do |c|
        if (c == token)
            yield val
            val = ""
        else
            val = val + c
        end
    end
    yield val
end

Examples:

myString = "Hello PlayMyCode How Are You Today?"
tokenize(myString, " ") do |seg|
    console(seg)
end

Hello
PlayMyCode
How
Are
You
Today?


console(subString(myString, myString.indexOf("PlayMyCode"), myString.indexOf("How")))


PlayMyCode


I'm sure that the PlayMyCode API will soon have these features, but for now the above will suffice.

Popular Posts