Posts tagged array

It Should Include Only One Of – An RSpec Matcher

0

I know RSpec tests should typically be implementation/data agnostic, but I ran into a situation in a unit test where I needed to make sure that the results of a query returned only one of the two records that were created during the setup but without knowing which record that would be ahead of time. This was due to the fact that the scoped finder returned a random record. So, I wrote a little matcher that lets me assert that a given array contains only one of a set of specified elements.

You can use it like so:

Join (implode) an Array of String Values with Formatting

1

In programming, I often need to join values together from an array. Typically this will be to do something on the backend, like join a list of integers together in a comma-delimited string for use in a SQL statement. For those times, the native join/implode functions work fine. Occasionally however, we need to finesse the resulting string to look a little more readable. I wrote a small function to do so. It’s called pretty_join()

Given an array of 0 or more values, pretty_join() will concatenate all of the values together using a common delimiter (a comma by default) except for the last two values which will be joined by the final separator (an ampersand by default).

Examples:

Find the longest common substring using PHP

1

I recently found a need to find the longest common substring in an array of strings in PHP. A couple of Google searches didn’t return any relevant solutions, so I decided to roll my own. I haven’t benchmarked this yet for large strings and/or arrays, but it does what I needed it to for my own purpose.

Example:

Go to Top