1. Home
  2. /
  3. Ruby
  4. /
  5. Blocks and Iterators

Blocks and Iterators - Ruby Typing CST Test

Loading…

Blocks and Iterators — Ruby Code

Demonstrates Ruby's elegant syntax with blocks, classes, and enumerable methods.

class Calculator
	def initialize
		@history = []
	end

	def add(a, b)
		result = a + b
		@history << "#{a} + #{b} = #{result}"
		result
	end

	def multiply(a, b)
		result = a * b
		@history << "#{a} * #{b} = #{result}"
		result
	end

	def history
		@history.each_with_index do |operation, index|
		puts "#{index + 1}. #{operation}"
		end
	end
end

# Array operations with blocks
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

even_numbers = numbers.select { |n| n.even? }
squares = numbers.map { |n| n ** 2 }
sum = numbers.reduce(0) { |acc, n| acc + n }

puts "Even numbers: #{even_numbers}"
puts "Squares: #{squares}"
puts "Sum: #{sum}"

# Calculator usage
calc = Calculator.new
calc.add(5, 3)
calc.multiply(4, 6)
calc.history

Ruby Language Guide

Ruby is a dynamic, object-oriented, high-level programming language designed for simplicity, productivity, and readability. It emphasizes developer happiness and convention over configuration, widely used for web development, scripting, automation, and backend systems.

Primary Use Cases

  • ▸Web application development (Ruby on Rails, Sinatra)
  • ▸Backend APIs and microservices
  • ▸Automation and scripting
  • ▸Prototyping and MVPs
  • ▸DevOps tooling (Chef, Puppet)
  • ▸Data processing scripts

Notable Features

  • ▸Everything is an object
  • ▸Dynamic typing and duck typing
  • ▸Powerful metaprogramming and DSL support
  • ▸Elegant and readable syntax
  • ▸Convention over configuration (Rails)
  • ▸Large ecosystem and gems library

Origin & Creator

Created by Yukihiro 'Matz' Matsumoto in 1995 in Japan. Designed to maximize developer happiness by blending Perl, Smalltalk, Eiffel, Ada, and Lisp influences into an elegant, readable syntax.

Industrial Note

Ruby dominates web startups, SaaS platforms, rapid prototyping, automation, and DevOps tooling (Chef, Puppet). Ruby on Rails accelerates development, making it a top choice for MVPs and web platforms like GitHub, Shopify, and Basecamp.

More Ruby Typing Exercises

Ruby Classes and InheritanceRuby Modules and MixinsRuby File HandlingRuby Exception HandlingRuby Hashes and SymbolsRuby Regular ExpressionsRuby Enumerables and MapRuby JSON ParsingRuby Time and Date Formatting

Practice Other Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#MqlCqlN1qlCypherGremlin