Do these two lines of code match? JavaScript versus Ruby

Using Ruby:

->  { 10.times {|i| puts i} }.call

For JavaScript:

(function (){
    for (i = 0; i<10; i++){
        console.log(i);
    }
})()

As someone with a background in JS, I found it interesting to learn about lambdas and Procs in Ruby, as they are functions without names that can be called. This concept reminded me of anonymous functions or Immediately Invoked Function Expressions (IIFE) in JavaScript.

Are these two examples similar? If not, what sets them apart?

Answer №1

These two statements are incredibly dissimilar in almost every way.

If we were to find the equivalent ECMAScript code for this Ruby snippet:

-> { 10.times {|i| puts i} }.call

It might look something like this:

(() => { 10.times(i => puts(i)) }).call()

However, since numbers cannot have methods in ECMAScript, a solution similar to the following is necessary:

(() => { times(10, i => puts(i)) }).call()

To make this work, we would need to include some extra Ruby library support code:

(() => { times(10, i => puts(i)) }).call()

function times(i, f) { if (i-- === 0) return; else { times(i, f); f(i) }}
function puts(s) { console.log(s) }

While still not identical to the original Ruby behavior, it's much closer compared to the alternative proposal:

  • Your approach introduces i into the global scope, whereas the Ruby code retains the variable as local to the inner block.
  • Ruby utilizes the method Proc#call rather than a function call operator, which ECMAScript also employs (Function.prototype.call).
  • Ruby uses a custom iteration method on Integer, while your ECMAScript suggestion involves a for loop.
  • In Ruby, Kernel#puts writes implicitly to the default output stream, while your ECMAScript version explicitly writes to the console.
  • self in Ruby is lexically bound, but in ECMAScript, this is dynamically tied to the function object unless an arrow function literal is used, ensuring lexical binding of this.

Conversely, the ECMAScript equivalent to:

(function (){
    for (i = 0; i<10; i++){
        console.log(i);
    }
})()

Might be represented by:

-> { $i = 0; while $i < 10 do $stdout.puts($i); $i += 1 end }.()

Once again, this is not completely analogous:

  • Ruby lacks a for loop and makes use of a while loop instead.
  • The call operator in Ruby is absent, with .() merely being syntactic sugar for the call method.
  • this in nested function expressions is dynamically bound, whereas self remains lexically bound in Ruby.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leverage the power of gRPC with Node.js and TypeScript for seamless

I'm trying to implement GRPC in a Node.js and Typescript project, but I'm facing an issue with generating proto files on Windows 10 using npm. I need to run the file transpile-proto-ts.sh: #!/usr/bin/env bash OUT_DIR="./src" TS_OUT_DIR="./src" ...

Leveraging mongo-triggers for automation

I just completed the installation of mongo-triggers by running: npm install mongo-triggers Now, I'm attempting to set up a simple "hello world" example: var MongoClient = require('mongodb').MongoClient; var triggers = require("mongo-trigg ...

Adding multiple text as label and sublabel in a React MUI Tooltip can be achieved by utilizing the appropriate

I'm struggling to incorporate a MaterialUI Tooltip into my React application with two separate text lines. The first line should serve as the main title, while the second line functions as a sublabel. In this screenshot provided, you can see where I ...

The responsiveness of Angular Material appears to be limited when tested in Chrome's debug mode for different devices

I have come across a peculiar issue. Within my HTML file, I have defined two attributes: Hide me on small devices Hide me on larger than small devices When I resize the window, the attributes work as intended. However, when I enter device debug mode ( ...

Combining items from the identical array in pairs using distinct identifiers

I have an array containing double values. const data = [ -0.003,-8.178509172818559E-16, 0.002,-1.3576469946421737E-15, 0.007,-1.2329107629591376E-1] I am looking to utilize these values in react-vis. The necessary syntax for data insertion in react-vis ...

Encountering an error when using AngularJS 1.7 with ES6 and webpack: Uncaught TypeError - Property 'module' is undefined

I am currently in the process of setting up the AngularJS app skeleton. Utilizing ES6 with webpack for bundling, I have encountered an error that has been difficult to resolve. The specific error message reads as follows: Uncaught TypeError: Cannot read ...

How come the values keep appearing without any loops or subsequent calls being made to the PHP file?

Here is a demo example showcasing 'Server Sent Events(SSE)': Embed HTML code(index.html) : <!DOCTYPE html> <html> <body> <h1>Receiving server updates</h1> <div id="result"></div> <script> if(type ...

How can you begin using version 4.4.0 of nuxtjs/axios in nuxt.js?

My plan is to incorporate the nuxtjs/axios module into my project. My first step is to install the module using npm: npm install nuxtjs/axios Next, I configure the settings in the nuxt.config.js file: modules: [ ['@nuxtjs/axios', { ba ...

Modifying embedded text using a variable

As a beginner coder, I was exploring youtube embeds and noticed they shared a common factor. I tried to utilize this common factor to choose which video to embed, but my code isn't working as expected. Below is the code I've written and any feedb ...

What is the method to escape from a for loop in Protractor?

Check out my code snippet: formElements[0].findElements(by.repeater(repeater)).then(function(items){ console.log(i, '>>>>>>>>>.No of items in the list --- '+items.length); (function(items){ ...

Managing form submissions in React with inputs spread across multiple components

I've been working on a ReactJS project with a form that is divided into multiple components. The main component imports all the child components, each containing input boxes, along with a submit button: My issue lies in trying to get all the componen ...

Tips for showing numbers in 2 decimal places while still storing them in 4 decimal places within Angular

I am currently involved in a project that requires precise number calculations, as well as a visually appealing display of these numbers to the users. Below is the HTML code snippet: <span> {{ getTotalStocksValue() }} %</span> <butto ...

Fixed Element Transitioning from Starting Position on Scroll

Check out the JSFiddle example here I'm currently working on a website utilizing Bootstrap 3. I have an image that sticks to the page when scrolling by changing its position to fixed. While this functionality works, the image tends to shift slightly ...

Looking to refresh the current page once an image has been successfully uploaded and the bootstrap model has been closed? Learn how to achieve this using cropper

I am working on a project that involves using cropperJS, jQuery, and PHP to upload cropped images. However, I have encountered an issue where after the upload is complete and the modal closes automatically, the display picture on the page does not update u ...

Effortless trending items formula for an online retail store using JavaScript

As I work on developing a small ecommerce website, my focus for the home page is to display products in order of popularity. The product schema includes important data such as: { ... noViews: Number, // Number of times a user has clicked on the produc ...

The use of Bootstrap carousel indicators effectively controls event propagation

One way to achieve the desired effect is by implementing a solution like the one provided in this example from Bootstrap. When interacting with the indicators quickly, the animations can stack on top of each other, resulting in a strange chain of events. ...

Create a new array by adding keys and their values to multiple documents

In my collection named inventory, I have multiple documents with values for each document. { "apples": 2 ,"oranges": 3, "carrots": 5 } { "apples": 4, "oranges": 6, "carrots": 9 } How can I combine all the fruits into a single array in multiple documents ...

Two approaches to discovering a set of items within an array that yield contrasting outcomes

Two different approaches are being used to solve this problem. "Determine a pair of numbers in an array that add up to a specific value" However, these methods are yielding distinct outcomes. What could be the reason behind this discrepancy? One method i ...

JavaScript template engines that rely on the DOM tree system

I am in search of a modern JavaScript template engine to upgrade from the outdated jQuery Template for my client-side templating requirements. I am leaning towards an approach where the template engine directly works with DOM trees instead of manipulating ...

Dynamic resizing navigation with JQUERY

I have successfully created a navigation menu that dynamically resizes each list item to fit the entire width of the menu using JavaScript. $(function() { changeWidth(500); function changeWidth(menuWidth){ var menuItems = $('#menu l ...