Ruby is the interpreted high-level programming language that supports various programming paradigms. It was designed with an emphasis on programming productivity and simplicity.
Ruby is an object-oriented language in the purest meaning possible because each value in the language behaves like (or is an object). Each object represents a particular class. An object responds to a set of methods defined by a class. Classes can extend, subclass, inherit, and override the methods of their superclass. Classes may also contain modules or inherit their methods from them. In this article, we will learn about Validating and Modifying Attribute Values in Ruby.
Objects and Classes
Ruby is an object-oriented programming language. The object-oriented concepts of inheritance, polymorphism, and classes are supported in Ruby. Ruby, however, is more advanced than other languages you may have used. One of the most permissive languages out there is Ruby; some languages are rigid, and some languages are permissive.
Validating and Modifying Attribute Values in Ruby
Let us look at a problem statement and its solution related to Validating and Modifying Attribute Values in Ruby.
Problem
You want to impose some control over the values assigned to your variables while still allowing outside code to set the instance variables of your objects. Before accepting new values, you might want a chance to test them out. Alternatively, you might wish to receive values in a format that is useful to the caller but change them so that they can be stored internally in a different format.
Solution
For each instance variable you wish to have control over, define your setter method. Quantity= would be the name of the setter method for an instance variable called quantity. A user can invoke the method object#quantity= with the input 10 by using a sentence like object.quantity = 10.
The quantity= method will determine if the instance variable quantity has to be set to 10. If an invalid value is supplied to a setter method, that method is free to raise an ArgumentException. It may also alter the provided value, transforming it into the class's preferred canonical form. Its final action ought to be to change the instance variable if it can obtain a suitable value.
We'll create a class that records the first and last names of individuals. Everybody must have a first and last name, and every first name must start with a capital letter. These two fairly arbitrary criteria are enforced via setter methods.
class Name
# Define default getter methods, but notsetter methods.
attr_reader :first, :last
# When someone tries to set a first name, enforce rules about it.
def first=(first)
if first == nil or first.size == 0
raise ArgumentError.new('The person must have a first name.')
end
first = first.dup
first[0] = first[0].chr.capitalize
@first = first
end
# When someone tries to set a last name, enforce rules about it.
def last=(last)
if last == nil or last.size == 0
raise ArgumentError.new('The person must have a last name.')
end
@last = last
end
def full_name
"#{@first} #{@last}"
end
# Delegate to the setter methods instead of setting the instance
# variables directly.
def initialize(first, last)
self.first = first
self.last = last
end
end
The Name class was built with the intention of enforcing the rules both during object creation and afterward:
jacob = Name.new('Jacob', 'Berendes')
jacob.first = 'Mary Sue'
jacob.full_name # => "Mary Sue Berendes"
john = Name.new('john', 'von Neumann')
john.full_name # => "John von Neumann"
john.first = 'john'
john.first # => "John"
john.first = nil
# ArgumentError: Everyone must have a first name.
Name.new('Kero, international football star and performance artist', nil)
# ArgumentError: Everyone must have a last name.
Analysis
Ruby forbids the access of one object to the instance variables of another. You are limited to calling methods. Ruby simulates instance variable access by facilitating the definition of getter and setter methods with names derived from the instance variable names.
When you call the method my var, which is actually invoked when you access object.my var, it just so happens to return a reference to the instance variable my var by default.
Similar to setting a new value for object.my_var, my_var= really acts as a setter method that receives the new value. Your new value might be immediately inserted into the instance variable my_var by that procedure. It can accept your value but secretly edit it, change the format, or do something else. It could be finicky and raise an ArgumentError to completely reject your value.
Frequently Asked Questions
What are an object and a class in Ruby?
Each object represents a particular class. An object responds to a set of methods defined by a class. Classes can extend, subclass, inherit, and override the methods of their superclass. Classes may also contain modules or inherit their methods from them.
What does Ruby forbid?
Ruby forbids the access of one object to the instance variables of another. You are limited to calling methods.
What is a range in Ruby?
A range is a type of object that has a starting and ending value and allows you to design sequences that span the entire range between these two values.
What is a nested hash?
We can use nested hashes to group or associate the data we're working with even more. They assist us in dealing with scenarios in which a category or piece of data is linked to a collection of values rather than a single discrete value.
What are a truthy value and falsy value?
In a boolean context, such as an if statement, it's a value considered True and false, respectively.
Conclusion
In this article, we have extensively discussed Validating and Modifying Attribute Values in Ruby.
We hope this blog has helped you enhance your knowledge regarding Validating and Modifying Attribute Values in Ruby.