Built-in Functions in Ruby Language
Ruby is a versatile and expressive programming language that provides a wide range of built-in functions (also
known as methods or functions) to make developers’ lives easier. These built-in functions are part of Ruby’s standard library and cover a variety of tasks, from basic operations to more advanced functionalities. In this post, we’ll explore some of the most commonly used built-in functions in Ruby and provide examples of how they can be used.puts
The puts
method is used to print a string or variable to the console with a newline character at the end. It’s commonly used for output in Ruby programs.
puts "Hello, World!"
gets
The gets
method is used to read input from the user via the console. It reads a line of text and returns it as a string.
print "Enter your name: "
name = gets.chomp
puts "Hello, #{name}!"
length
The length
method is used to find the length of a string, array, or other enumerable objects.
string = "Ruby is fun!"
puts "Length of the string: #{string.length}"
to_s
, to_i
, to_f
These methods are used for type conversion. to_s
converts an object to a string, to_i
to an integer, and to_f
to a floating-point number.
num = 42
puts num.to_s
str = "3.14"
puts str.to_f
split
The split
method splits a string into an array of substrings based on a delimiter.
sentence = "Ruby is a beautiful language"
words = sentence.split(" ")
puts words
join
The join
method combines the elements of an array into a single string, separated by a specified delimiter.
colors = ["red", "green", "blue"]
combined = colors.join(", ")
puts combined
each
The each
method is used for iterating over elements in an array or other enumerable objects.
fruits = ["apple", "banana", "cherry"]
fruits.each do |fruit|
puts "I love #{fruit}s!"
end
map
The map
method applies a block of code to each element in an array and returns a new array with the results.
numbers = [1, 2, 3, 4, 5]
squared_numbers = numbers.map { |n| n * n }
puts squared_numbers
include?
The include?
method checks if an array or string includes a specific element or substring.
colors = ["red", "green", "blue"]
puts colors.include?("green") # true
sort
The sort
method arranges elements in an array in ascending order.
numbers = [5, 2, 8, 1, 9]
sorted_numbers = numbers.sort
puts sorted_numbers
These are just a few examples of the many built-in functions available in Ruby. Understanding these functions and how to use them effectively can greatly simplify your Ruby programming tasks. As you explore Ruby further, you’ll discover many more useful built-in functions that can help you write efficient and expressive code.
Discover more from PiEmbSysTech
Subscribe to get the latest posts sent to your email.