Classes in Ruby can be easily modified. The above code adds the like_a_cow method to String... So now the whole program can make a string "moo", like above.
He/Him; Senior Software Developer, IT Swiss-army-knife.
Lots of coding, some hardware, some devops & sysops, some micro-controller electronics.
I used Arch BTW :)
I use extensions a lot on sealed library classes to add Quality Of Life things. One example is creating cleaner methods for adding parameters to SQLClient ClientCommand objects as one liners instead of multi-command monstrosities. (ok, they aren't that big, but do look unclean)
I think it's different (safer) in C# though, right? Like you need to add using <namespace> for the new methods to be accessible. So it's not true monkey patching, which is generally dangerous and best avoided.
He/Him; Senior Software Developer, IT Swiss-army-knife.
Lots of coding, some hardware, some devops & sysops, some micro-controller electronics.
I used Arch BTW :)
Indeed you would need to use the containing namespace. And are likely safer as it would be pretty hard to modify the behaviour of code outside of your intended changes. (I think you would have to try very hard to have any affect outside of your explicit calls to the extension methods)
I won't claim to know much about TRUE monkey patching, but wikipedia's Extension Methods and Monkey Patching articles do reference each other in suggestive ways. ;)
Full-time web dev; JS lover since 2002; CSS fanatic. #CSSIsAwesome
I try to stay up with new web platform features. Web feature you don't understand? Tell me! I'll write an article!
He/him
One of the most salient features of our Tech Hiring culture is that there is so much bullshit. Everyone knows this. Each of us contributes his share. But we tend to take the situation for granted.
EDIT: A big advantage with for example the JavaScript version monkey-patching String.prototype, is that the String class is not modified everywhere in your codebase.
Hi! I'm an aspiring Software Engineer currently studying at the University of St Andrews in Scotland. I'm mostly interested in full-stack web development and anything that involves lots of data.
In Rust you can add functions to other types with traits. This actually adds the like_a_cow function for all types that are printable, including strings. You have to use the trait though.
pubtraitLikeACow{fnlike_a_cow(&self)->String;}impl<T:std::fmt::Display>LikeACowforT{fnlike_a_cow(&self)->String{format!("Moo {} mooooo",&self)}}fnmain(){// need to `use LikeACow;` if used in other modules, but not here.lets="hello";println!("{}",s.like_a_cow());}
After my first contact with a computer in the 1980's, I taught myself to program in BASIC and Z80 assembler. I went on to study Computer Science and have enjoyed a long career in Software Engineering.
Now that I'm staring at this chart, I'm recalling that at some point I was trying to parse markdown. Pretty sure this is looking for nested lists:
* Hello!
1. A nested ordered list
Though, it is interesting to me that the initial * or \d\. is not captured; one would think it'd be important to distinguish between an unordered and ordered list...
After my first contact with a computer in the 1980's, I taught myself to program in BASIC and Z80 assembler. I went on to study Computer Science and have enjoyed a long career in Software Engineering.
I studied the screenshot I attached to my comment and came to the same conclusion but it looks to me the expression might be more complicated than it needs to be - without fully understanding the context of course.
In PHP, the division operator / returns an integer if the two operands are both integers and divide exactly, and a float in all other cases. (10 / 2) thus gives int(5), while (11 / 2) gives float(5.5). Then, in the next division step, 5 / 5 gives int(1), while 5.5 / 5.5 gives float(1).
All right, let's see if you guys have a clue about this:
docker commit `docker ps -a |\head-n2 |\tail-n1 |\cut-d" "-f1`$1:$2
This is a single line of shellscript code written over three lines for readability. Notice that it employs backticks inside the code.
A lot is happening here, obviously. FIrst of all, the $1 and $2 will be replaced by the first and second command line argument respectively. So if you are invoking this script with the command line arguments repo and tag, this will translate to:
docker commit `docker ps -a |\head-n2 |\tail-n1 |\cut-d" "-f1` repo:tag
Next, note the backticks inside the command. The portion between the backticks - will first be evaluated. The result of this evaluation will then replace the entire thing inside the backticks.
Now, what does the portion inside the backtick do? Well, it has four parts:
Part 1 is docker ps -a, which yields a list of Docker images and their details:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
20d03205fe06 ubuntu:20.04 "bash" 3 seconds ago Exited (0) 2 seconds ago bold_feynman
dcf460b2c4ff 07cd54330caf "/bin/sh -c 'tar xzf…" 4 minutes ago Up 4 minutes blissful_liskov
This output is then piped into part 2. Piping is a special construct in Shellscript, which takes the string output of one command and puts it into the string input of the next command. So if command-1 prints 2+2+2 into the output, and command-2 evaluates mathematical expressions from keyboard and prints the output, then command-1 | command-2 will basically make the 2+2+2 from the first command become the input of the second, and we will only see the final output - 6.
The output of the first command is being piped into the second command, which is head -n2. The head command snipes out the first n lines from a file (or text input), and prints it. When fed the lines of details of different classes at the input, the head command will print the first n lines and then ignore the rest. We specify n with the -n2 flag, and its value is set to 2.
So the head command will print the first two lines from the table:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
20d03205fe06 ubuntu:20.04 "bash" 3 seconds ago Exited (0) 2 seconds ago bold_feynman
Notice that this includes the heading row and the details of the latest image - in this case, one which was created just three seconds before this command was run (I admit to having created it just to demonstrate this snippet).
The next command in the pipe is tail, and this command will ignore all but the last n lines from the input, and print those last n lines. In this case, we invoke it with tail -n1, thereby setting n to 1. The last one line will be printed.
20d03205fe06 ubuntu:20.04 "bash" 3 seconds ago Exited (0) 2 seconds ago bold_feynman
Or at least, tail will try to print it. But its own printed output has been further piped into the cut command. This command does something quite whacky: it takes two arguments, known as the delimiter and the selected columns. The delimiter has to be a char and the selected columns is a comma-separated sequence of numbers. In case a single number is provided, that single number is interpreted as a single-length sequence of numbers.
What cut does is that it splits each line of its input into parts, separated by the delimiter. It then takes the specific values which correspond to the selected columns, and then prints only those values which have been selected.
For instance, in this case, it will split the input string (which is a single line) by the " " space character, and then take out the first member of the resulting array of substrings. Of course, this effectively means that it will only pick the first word of the line. And in this case, that word is the container ID of the most recently run container:
20d03205fe06
This ID is the final output of the entire portion inside the backticks, and given the way Shellscript works, the entire portion inside backticks will simply be replaced by this one container ID number:
docker commit 20d03205fe06 repo:tag
Which is the final form of the command, and it is executed. So the command does this:
It commits the most recently run container as an image with the name and tag provided as command line arguments to the script
This is an F# script that posts a Post like object to the json placeholder API and deserializes the json response to a Post.
you can copy into a file and run it like this:
dotnet fsi ./filename.fsx
#r"nuget: FsHttp"// specify the http library// open the required namespacesopenFsHttpopenFsHttp.DslCEopenSystem.Text.Json// define the shape of the data// these are known as Records in F#typePost={userId:intid:inttitle:stringbody:string}// In F# records can't have null values for most types// so we use an anonymous record (`{| |}` instead of `{}`)// because we don't have an id value yetletpayload=JsonSerializer.Serialize({|userId=1title="Sample"body="Content"|})letresponse=// declare the requesthttp{POST"https://jsonplaceholder.typicode.com/posts"bodyjsonpayload}// send the request, it can also be done asynchronously|>Request.send// get the stream back (rather than downloading the response in bytes/string|>Response.toStream// deserialize it using .NET base class library classes like JsonSerializer|>JsonSerializer.Deserialize<Post>// you can now check the response in the consoleprintfn"%A"response
Does a binary search through an array and finds the first element with a value greater than a random target at index 0.
This is a part of a script that chooses a random set of items to put in a supply box where each item set can have a weight assigned to it based on how valuable the items are (higher weight means more common)
Aspiring Rustacean. Whatever-Stack developer who fell in love with React and GraphQL. Addicted to CTRL + ⎵. Building tools to improve developers experience.
Top comments (64)
I'll go first with Ruby
Classes in Ruby can be easily modified. The above code adds the
like_a_cow
method toString
... So now the whole program can make a string "moo", like above.In JavaScript it's:
I wonder how many languages allow this?
C# allows this,
you can now use this as
I use extensions a lot on sealed library classes to add Quality Of Life things. One example is creating cleaner methods for adding parameters to SQLClient ClientCommand objects as one liners instead of multi-command monstrosities. (ok, they aren't that big, but do look unclean)
I think it's different (safer) in C# though, right? Like you need to add
using <namespace>
for the new methods to be accessible. So it's not true monkey patching, which is generally dangerous and best avoided.Indeed you would need to use the containing namespace. And are likely safer as it would be pretty hard to modify the behaviour of code outside of your intended changes. (I think you would have to try very hard to have any affect outside of your explicit calls to the extension methods)
I won't claim to know much about TRUE monkey patching, but wikipedia's Extension Methods and Monkey Patching articles do reference each other in suggestive ways. ;)
Python:
I should add that this is not good practice.
str
is a built in function and you should not override it.I'll do you one better: if you define a dynamic getter using
Object.defineProperty
, you can make it look exactly like the Ruby example:Same thing in Kotlin, super handy.
EDIT: A big advantage with for example the JavaScript version monkey-patching String.prototype, is that the
String
class is not modified everywhere in your codebase.It works like a normal function, you import the new function only if and where you need it. See kotlinlang.org/docs/extensions.htm...
In Dart it's
Similar in Scala:
In Rust you can add functions to other types with traits. This actually adds the
like_a_cow
function for all types that are printable, including strings. You have touse
the trait though.Nice example, but I think it could be refined somewhat
It is bad practice to do such things. Better use
and add in you class
Some regex I wrote in 2018:
I've stared at it for 5 minutes and still can't tell you what's happening 🙃
If you throw the expression into something like Debuggex it can map out the routes through the expression, as follows.
However, whilst this shows what is happening it does not indicate why.
Now that I'm staring at this chart, I'm recalling that at some point I was trying to parse markdown. Pretty sure this is looking for nested lists:
Though, it is interesting to me that the initial
*
or\d\.
is not captured; one would think it'd be important to distinguish between an unordered and ordered list...I studied the screenshot I attached to my comment and came to the same conclusion but it looks to me the expression might be more complicated than it needs to be - without fully understanding the context of course.
It searches for indented sublists, like:
You're welcome.
Anyone that can read this and know exactly what's going on is clearly not human
Which purpose u wrote this regex
PHP
Prints
1 1 no
.In PHP, the division operator
/
returns an integer if the two operands are both integers and divide exactly, and a float in all other cases.(10 / 2)
thus givesint(5)
, while(11 / 2)
givesfloat(5.5)
. Then, in the next division step,5 / 5
givesint(1)
, while5.5 / 5.5
givesfloat(1)
.PHP's language design is truly astounding.
All right, let's see if you guys have a clue about this:
This is a single line of shellscript code written over three lines for readability. Notice that it employs backticks inside the code.
A lot is happening here, obviously. FIrst of all, the
$1
and$2
will be replaced by the first and second command line argument respectively. So if you are invoking this script with the command line argumentsrepo
andtag
, this will translate to:Next, note the backticks inside the command. The portion between the backticks - will first be evaluated. The result of this evaluation will then replace the entire thing inside the backticks.
Now, what does the portion inside the backtick do? Well, it has four parts:
Part 1 is
docker ps -a
, which yields a list of Docker images and their details:This output is then piped into part 2. Piping is a special construct in Shellscript, which takes the string output of one command and puts it into the string input of the next command. So if
command-1
prints2+2+2
into the output, andcommand-2
evaluates mathematical expressions from keyboard and prints the output, thencommand-1 | command-2
will basically make the2+2+2
from the first command become the input of the second, and we will only see the final output -6
.The output of the first command is being piped into the second command, which is
head -n2
. Thehead
command snipes out the first n lines from a file (or text input), and prints it. When fed the lines of details of different classes at the input, thehead
command will print the firstn
lines and then ignore the rest. We specifyn
with the-n2
flag, and its value is set to2
.So the
head
command will print the first two lines from the table:Notice that this includes the heading row and the details of the latest image - in this case, one which was created just three seconds before this command was run (I admit to having created it just to demonstrate this snippet).
The next command in the pipe is
tail
, and this command will ignore all but the lastn
lines from the input, and print those lastn
lines. In this case, we invoke it withtail -n1
, thereby settingn
to1
. The last one line will be printed.Or at least,
tail
will try to print it. But its own printed output has been further piped into thecut
command. This command does something quite whacky: it takes two arguments, known as the delimiter and the selected columns. The delimiter has to be a char and the selected columns is a comma-separated sequence of numbers. In case a single number is provided, that single number is interpreted as a single-length sequence of numbers.What
cut
does is that it splits each line of its input into parts, separated by the delimiter. It then takes the specific values which correspond to the selected columns, and then prints only those values which have been selected.For instance, in this case, it will split the input string (which is a single line) by the
" "
space character, and then take out the first member of the resulting array of substrings. Of course, this effectively means that it will only pick the first word of the line. And in this case, that word is the container ID of the most recently run container:This ID is the final output of the entire portion inside the backticks, and given the way Shellscript works, the entire portion inside backticks will simply be replaced by this one container ID number:
Which is the final form of the command, and it is executed. So the command does this:
Wow.... That's actually quite useful
Thank you. I use this one a lot, though I typically write it out in just one line.
Here's a Rust moment, I tweeted it today lol
Is your text editor or some plugin showing the return types of the functions in the chain? That's pretty cool. What's the plugin/editor?
I'm using VScode with rust-analyzer extension
Nothing in c++
This is an F# script that posts a Post like object to the json placeholder API and deserializes the json response to a Post.
you can copy into a file and run it like this:
dotnet fsi ./filename.fsx
Does a binary search through an array and finds the first element with a value greater than a random target at index 0.
This is a part of a script that chooses a random set of items to put in a supply box where each item set can have a weight assigned to it based on how valuable the items are (higher weight means more common)
what language is that?
SQF :D
I'm gonna bet on Brainf*ck, so here's mine.
Please don't ask what it does, cause I've no idea, it just looks cool..I guess.
BASIC hacking
Some comments may only be visible to logged-in visitors. Sign in to view all comments.