Author: saqibkhan

  •  Inclusion

    You need to include the CSS file in your HTML document before using it. There are multiple ways to include CSS in an HTML file, such as writing inline CSS, internal CSS, or including a CSS file.

    Styles can be associated with your HTML document in different ways, such as:

    • Inline CSS − The CSS styling is placed inside an HTML element tag, which has an effect only on that element.
    • Internal CSS − The CSS styling is placed inside the <style> tag, under the <head> tag.
    • External CSS − The CSS styling is placed in an external file (.css extension) inside the <link> tag, under the <head> tag.

    Embedded / Inline CSS – <style> Attribute

    You can use style attribute of any HTML element to define style rules. These rules will be applied to that element only.

    Syntax

    Here is the generic syntax −

    <element style = "...style rules....">

    The value of style attribute is a combination of style declarations separated by semicolon (;).

    Example

    The following example demonstrates the use of inline css styling:

    <html><head></head><body><div style = "border: 5px inset gold; background-color: black; width: 300px; text-align: center;"><h1 style = "color:#36C;">Hello World !!!</h1><p style = "font-size: 1.5em; color: white;">This is a sample CSS code.</p></div></body></html>

    Internal CSS – <style> Element

    You can put your CSS rules into an HTML document using the <style> element. This tag is placed inside the <head>…</head> tag. Rules defined using this syntax will be applied to all the elements available in the document.

    Syntax

    Here is the generic syntax −

    <head><style type = "text/css">
    
      h1 {
         color: #36CFFF; 
      }
      p {
         font-size: 1.5em;
         color: white;
      }
      div {
         border: 5px inset gold;
         background-color: black;
         width: 300px;
         text-align: center;
      }
    </style></head>

    Example

    The same style is applied in the following example:

    <html><head><style type = "text/css">
    
      h1 {
         color: #36CFFF; 
      }
      p {
         font-size: 1.5em;
         color: white;
      }
      div {
         border: 5px inset gold;
         background-color: black;
         width: 300px;
         text-align: center;
      }
    </style></head><body><div><h1>Hello World !!!</h1><p>This is a sample CSS code.</p></div></body></html>

    Attributes associated with <style> elements are −

    AttributePossible ValuesDescription
    typetext/cssSpecifies the style sheet language as a content-type (MIME type). This is a required attribute.
    mediascreenttytvprojectionhandheldprintbrailleauralallSpecifies the device the document will be displayed on. Default value is all. This is an optional attribute.

    External CSS – <link> Element

    The <link> element can be used to include an external stylesheet file in your HTML document.

    An external style sheet is a separate text file with .css extension. You can define all the style rules in this text file and include this file in any HTML document using the <link> element.

    Syntax

    Here is the generic syntax of including external CSS file −

    <head><link type = "text/css" href = "..." media = "..." /></head>

    Attributes associated with <style> elements are −

    AttributePossible ValuesDescription
    typetext cssSpecifies the style sheet language as a content-type (MIME type). This attribute is required.
    hrefURLSpecifies the style sheet file having style rules. This attribute is required.
    mediascreenttytvprojectionhandheldprintbrailleauralallSpecifies the device the document will be displayed on. Default value is all. This is an optional attribute.

    Create a style sheet file with a name ext_style.css having the following rules −

       h1 {
    
      color: #36CFFF; 
    } p {
      font-size: 1.5em;
      color: white;
    } div {
      border: 5px inset gold;
      background-color: black;
      width: 300px;
      text-align: center;
    }

    Example

    Now you can include this file ext_style.css in any HTML document as follows −

    <head><link type = "text/css" href = "ext_style.css"/></head>

    Following example demonstrates how to include an external css file in an HTML file:

    <html><head><link type = "text/css" href = "ext_style.css"/></head><body><div><h1>Hello World !!!</h1><p>This is a sample CSS code.</p></div></body></html>

    Imported CSS – @import Rule

    The @import is used to import an external stylesheet in a manner similar to the <link> element. The only key point to remember is, the @import rule must be declared on top of the document. Here is the generic syntax of @import rule.

    Syntax

    Refer the following two css files − style.css and demostyle.css

    style.css

    body {
       background-color: peachpuff;
    }
    

    demostyle.css

    @import url("style.css");
    
    h1 {
    
      color: #36CFFF; 
    } p {
      font-size: 1.5em;
      color: white
    } div {
      border: 5px inset gold;
      background-color: black;
      width: 300px;
      text-align: center
    }

    You just need to include the stylesheet, that has @import rule defined, in the <link> tag in the HTML document as follows −

    <head><link type = "text/css" href = "demostyle.css"></head>

    Example

    Following example demonstrates the use of @import rule, where one stylesheet can be imported into another stylesheet:

    <html><head><link type = "text/css" href = "demostyle.css"></head><body><div><h1>Hello World !!!</h1><p>This is a sample CSS code.</p></div></body></html>

    CSS Rules Overriding

    We have discussed different ways to include style sheet rules in an HTML document. Here is the rule to override any Style Sheet Rule.

    • Any inline style sheet takes highest priority. So, it will override any rule defined in <style>…</style> tags or rules defined in any external style sheet file.
    • Any rule defined in <style>…</style> tags will override rules defined in any external style sheet file.
    • Any rule defined in external style sheet file takes lowest priority, and rules defined in this file will be applied only when above two rules are not applicable.

    CSS Comments Inclusion

    Many times, you may need to put additional comments in your style sheet blocks. So, it is very easy to comment any part in style sheet. You can simple put your comments inside /*…..this is a comment in style sheet…..*/.

    You can use /* ….*/ to comment multi-line blocks.

    Example

    <html><head><style>
    
      h1 {
         color: #36CFFF; 
      }
      p {
         font-size: 1.5em;
         color: red;
         /* This is a single-line comment */
         text-align: center;
      }
      
      div {
         border: 5px inset gold;
         /* This is a multi-line comment
         background-color: black;
         width: 300px;
         text-align: center;
         */
      }
    </style></head><body><div><h1>Hello World !!!</h1><p>This is a sample CSS code.</p></div></body></html>

  • Syntax

    CSS stands for Cascade Style Sheet is popular stylesheet language used to design an interactive webpage. In this tutorial we will learn CSS syntax and usages of CSS along with HTML.

    CSS Syntax

    Following is the syntax of styling using CSS.

    selector{property: value;}
    • Selector: CSS selectors are used to select the HTML element or groups of elements you want to style on a web page.
    • Property: A CSS property is an aspect or characteristic of an HTML element that can be styled or modified using CSS, such as color, font-size, or margin.
    • Value: Values are assigned to properties. For example, color property can have value like red, green etc.

    For Example:

    Syntax

    Multiple Style Rules

    If you want to define multiple rules for a single selectors you can specify those in single block separated by a semicolon (;).

    Syntax

    selector{property1: value1;property2: value2;property3: value3;}

    Now let us look an example for styling using CSS.

    Example

    <!DOCTYPE html><html><head><style>
    
        /* Style all the paragraphs */
        p {
            background-color: black;
            color: white; 
            padding: 5px;
        }
        /* Style all elements with class 'special' */
        .special {
            color: lightblue; /* Change text color */
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;p&gt;
        This a normal paragraph...
    &lt;/p&gt;&lt;br&gt;&lt;p class="special"&gt;
        This is a paragraph with class special...
    &lt;/p&gt;&lt;br&gt;&lt;div class="special"&gt;
        This is a div with class special...
    &lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    CSS Selectors Syntax

    CSS Selectors are used to select the HTML elements you want to style on a web page. They allow you to target specific elements or groups of elements to apply styles like colors, fonts, margins, and more. Different types of selectors are mentioned below:

    Universal Selector

    Universal selectors select and apply styles to all elements in an HTML document.

    *{font-family: Verdana, sans-serif;color: green;}

    Element Selectors

    Element selectors select specific HTML elements.

    h1{color: #04af2f;}

    Class Selectors

    Class selectors select and style an element with a specific value for its class attribute.

    .myDiv{color: #04af2f;}

    Id Selectors

    Id selectors select a single element with a particular value for the id attribute.

    #myDiv{color: #04af2f;}

    Attribute Selectors

    Attribute selectors select an element based on a specific attribute value.

    a[target]{background-color: peachpuff;}

    Example: This example demonstrates the types of selectors mentioned above.

    <!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;title&gt;CSS Selector&lt;/title&gt;
    &lt;style&gt;
        *{background-color: #04af2f;color: white;}h3{text-align: center;}#myDiv{height: 200px;width: 200px;background-color: antiquewhite;color: black;}.para{border: 1px solid black;}a[href]{font-size: 2em;color: red;}
    &lt;/style&gt;
    </head> <body>
    &lt;h3&gt;CSS selectors Example&lt;/h3&gt;
    &lt;div id="myDiv"&gt;This is a div element.&lt;/div&gt;
    &lt;p class="para"&gt;This is a paragraph element.&lt;/p&gt;
    &lt;a href="/css/css_padding.htm" target="_blank"&gt;This is a Link&lt;/a&gt;
    </body> </html>

    CSS Grouping and Nesting Syntax

    Grouping and nesting selectors allow us to apply the same style to multiple elements at a time.

    CSS Grouping Selector Syntax

    Grouping selectors are comma-separated and used to select multiple elements and style them at a time.

    div, p{background-color: #04af2f;color: white;}

    CSS Nesting Syntax

    Nesting allows the nesting of one specific style rule within another.

    div p{background-color: #04af2f;color: white;font-size: 20px;letter-spacing: 1px;}

    CSS Pseudo-Classes & Pseudo-Elements Syntax

    Pseudo-class and pseudo-element, both select specific types of elements. The pseudo class defines the style for a specific state while the pseudo element targets a specific part of an element./p>

    CSS Pseudo-Element Syntax

    CSS pseudo-element styles specific parts of an element.

    p:before{content:"NOTE:";font-weight: bold;}

    CSS Pseudo-Class Syntax

    CSS pseudo-class in CSS is used to select and style elements based on their state.

    a:hover{color: red;}

    CSS Inclusion Syntax

    CSS can be used in any HTML document using three different methods which are: inline CSSinternal CSS, and external CSS.

    Inline CSS Syntax

    Inline CSS are used directly within HTML tags.

    <div style="color: #04af2f;">Welcome to TutorialsPoint.</p>

    Internal CSS Syntax

    Internal CSS is used within the head section of an HTML document using a style tag.

    <style>
    
    body {
        background-color: #04af2f;
    }
    </style>

    External CSS Syntax

    External CSS is written in a separate file having a .css extension and linked to the HTML document using link tag.

    <link rel="stylesheet" type="text/css" href="style.css">

    CSS Media Queries Syntax

    CSS media queries apply different CSS styles based on the screen size, resolution, and other characteristics and are often used for creating responsive designs.

    @media (max-width: 700px){body{background-color: #04af2f;}}

    CSS Variables Syntax

    CSS Variables allows to store and reuse values throughout the CSS program.

    :root{--main-color: #04af2f;}

    CSS Comments Syntax

    CSS comments add an explanatory note about the code.

    /* This is a single line CSS comment *//* This is 
    a multi-line
    CSS comment 
    */

  • Introduction

    CSS is acronym of Cascading Style Sheets. It helps to define the presentation of HTML elements as a separate file known as CSS file having .css extension.

    What is CSS?

    • CSS stands for Cascading Style Sheets, used to describe the presentation and design of a web pages.
    • Using CSS, you can control the color of the text, the style of fonts, the spacing between paragraphs, how columns are sized and laid out, what background images or colors are used.
    • CSS can control the layout of multiple web pages all at once.

    CSS Styling Example

    Following is layout of a webpage, click the button below to add CSS styling to the page and see difference between a webpage with and without CSS.Add CSS

    Webpage Layout

    Sidebar

    Sidebar content here.

    Click to Add Style

    You can toggle between styled version and unstyled version of this page using above button.

    © 2024 Webpage Layout. All rights reserved.

    Why Use CSS?

    • CSS Saves Time: You can write CSS once and then reuse same sheet in multiple HTML pages.
    • Pages Load Faster: If you are using CSS, you do not need to write HTML tag or attributes every time. Just write one CSS rule of a tag and apply it to all the occurrences of that tag.
    • Easy Maintenance: To make a global change, simply change the style, and all elements in all the web pages will be updated automatically.
    • Superior Styles to HTML: CSS has a much wider array of attributes than HTML, so you can get a far better look to your HTML page.
    • Multiple Device Compatibility: For the same HTML document, different versions of a website can be presented for different screen widths
    • Global Web Standards: Now most of the HTML attributes are being deprecated and it is being recommended to use CSS.

    CSS Syntax

    Syntax of CSS consist of selectors and declaration used to apply styles to HTML elements.

    selector{property: value;}
    • The selector targets the HTML element/elements that you want to style.
    • The declaration block contains one or more declarations enclosed in curly braces {}.
    • Each declaration consists of a property and a value separated by a colon :. Declarations are separated by semicolons ;.

    There are several types of selectors available in CSS, commonly used selectors are classes, IDs and tags. To know complete list of selectors visit CSS Selectors article.

    CSS History and Versions

    Current version of CSS3 and early versions were CSS1 and CSS2. As of now CSS is continuesly evolving and adapting new capabilities that full fills the current website’s requirements.

    CSS-versions

    Cascading Style Sheets level 1 (CSS1) came out of W3C as a recommendation in December 1996. This version describes the CSS language as well as a simple visual formatting model for all the HTML tags.

    CSS2 became a W3C recommendation in May 1998 and builds on CSS1. This version adds support for media-specific style sheets e.g. printers and aural devices, downloadable fonts, element positioning and tables.

    CSS3 was became a W3C recommendation in June 1999 and builds on older versions CSS. It has divided into documentations is called as Modules and here each module having new extension features defined in CSS2.

    CSS3 Modules

    CSS3 Modules are having old CSS specifications as well as extension features.

    • Selectors
    • Box Model
    • Backgrounds and Borders
    • Image Values and Replaced Content
    • Text Effects
    • 2D and 3D Transformations
    • Animations
    • Multiple Column Layout
    • User Interface

    For a quick guide on types of style used in CSS, visit our CSS cheat-sheet

  • Roadmap

    This Roadmao provides you the complete steps to use CSS styles to build web applications. This will helps you to learn the core concepts of CSS. You will learn core concepts, advanced techniques, and best practices by following mentioned topics.

    What is a Tutorial Roadmap?

    Tutorial Roadmap typically covers the journey from beginner to advanced user, including key concepts, practical applications, and best practices.

    CSS Roadmap

    Master CSS from beginner to expert with our comprehensive 2024 roadmap. Learn essential concepts, modern techniques, and best practices. Includes practical examples, learning resources, and a structured timeline for becoming a CSS expert.

    CSS Roadmap

    CSS Introduction

    CSS Selectors

    CSS Colors

    CSS Opacity

    CSS Backgrounds

    CSS Box Model

    CSS Syntax

    CSS Inclusion

    CSS Text

    CSS Fonts

    CSS Styling Lists

    CSS Display

    CSS Visibility

    CSS Positioning

    CSS Float

    CSS Flexbox

    CSS Grid

    CSS Media Queries

    CSS Transition

    CSS Transformation

    CSS Animation

    CSS Units

    Types of Selectors

    CSS Comments

    CSS Color Reference

    CSS Background Color

    CSS Background Image

    Background Image Properties

    CSS Margins

    CSS Paddings

    CSS Borders

    CSS Dimension

    Text Properties

    Font Properties

    List Style Properties

    Display Property Values

    Position Properties

    Flex Container Properties

    Flex Items Properties

    Grid Properties

    How this Roadmap Can help you?

    This Roadmap will help you to calculate the time will be required to complete this tutorial by visualizing the steps when you can implement a strategic plan and to better understand the concepts. After completing the mentioned topics keep practicing to improve yourself.

  • CSS Tutorial

    What is CSS

    CSS is the acronym for “Cascading Style Sheet”. It’s a style sheet language used for describing the presentation of a document written in a markup language like HTML. CSS helps the web developers to control the layout and other visual aspects of the web pages. CSS plays a crucial role in modern web development by providing the tools necessary to create visually appealing, accessible, and responsive websites.

    CSS Versions

    Since the inception of CSS, several versions have came into existence. Some of the notable versions include:

    • CSS1 (Cascading Style Sheets Level1) – The initial version of CSS, released in December 1996. CSS1 provided basic styling capabilities for HTML documents, including properties for text, colors, backgrounds, margins, and borders.
    • CSS2 (Cascading Style Sheets Level2) – Released in May 1998, CSS2 introduced new features such as positioning, z-index, media types, and more advanced selectors like attribute selectors and child selectors.
    • CSS2.1 – The version 2.1, published as a W3C Recommendation in June 2011, clarified and refined CSS2, addressing inconsistencies and ambiguities in the specification. CSS2.1 focused on improving interoperability among web browsers.
    • CSS3 (Cascading Style Sheets Level 3) – CSS3 is a collection of modules that extend the capabilities of CSS. It introduces numerous new features and enhancements, including advanced selectors, multiple column layouts, animations, transformations, gradients, shadows, and more.
    • CSS4 (Cascading Style Sheets Level 4) – CSS4 is an ongoing effort to extend CSS3 with new features and enhancements.

    Each version of CSS builds upon the previous ones, adding new features and refining existing capabilities to meet the evolving needs of web developers and designers. CSS is referred as just CSS now, without a version number.

    Types of CSS

    1. Inline CSS: Inline CSS is applied directly to an HTML element using the style attribute. It has the highest priority among the three methods.
      Example
    2. <p style=”color: blue; font-size: 16px;”> This line is an inline-styled paragraph. </p>
    3. Internal CSS: Internal CSS is defined within the <style> tag inside the <head> section of an HTML document.
      Example
    4. <head><style> p { color: green; font-size: 18px; } </style></head><body><p>This line is styled using internal CSS.</p></body>
    5. External CSS: External CSS is written in a separate .css file and linked to the HTML document using the <link> tag. This is the recommended method for large projects as it improves maintainability.
      Example<!– HTML file –><head><link rel=”stylesheet” href=”styles.css”></head><body><p>This line is styled using external CSS.</p></body>/* styles.css */ p { color: red; font-size: 20px; }

    Advantages of Using CSS

    • Responsive design – CSS offers features like media queries that enable developers to create responsive layouts that adapt to different screen sizes and devices, ensuring a consistent user experience.
    • Flexibility and Control – CSS provides precise control over the presentation of HTML elements, allowing developers to customize layout, typography, colors, and other visual properties.
    • Consistency and Reusability – Developers can ensure consistency across the entire website, by defining styles in a central CSS file. Styles can be reused across multiple pages, reducing redundancy and making updates easier.
    • Search Engine Optimization (SEO) – CSS can be used to structure content in a way that improves search engine visibility.
    • Ease of Maintenance – Centralized CSS files make it easier to maintain and update styles across a website. Changes can be applied globally, ensuring uniformity and reducing the risk of inconsistencies.
    • Faster Page Loading – External CSS files can be cached by browsers, resulting in faster page loading times for subsequent visits to a website. This caching mechanism reduces server load and bandwidth consumption.

    Components of CSS

    CSS works by associating rules with HTML elements. A CSS rule contains two main parts:

    • selector which specifies the HTML element(s) to style.
    • declaration block which contains one or more declarations separated by semicolons.

    Each declaration includes a property name and a value, specifying the aspect of the element’s presentation to control.

    CSS Example

    Just to give you a little excitement about CSS, here is a sample CSS snippet for your reference.

    <html><head><title>CSS Tutorial</title><style>
    
      h1 {
         color: #36CFFF; 
      }
      p {
         font-size: 1.5em;
         color: white;
      }
      div {
         border: 5px inset gold;
         background-color: black;
         width: 300px;
         text-align: center;
      }
    </style></head><body><div><h1>Hello World!</h1><p>This is a sample CSS code.</p></div></body></html>

    In the above CSS snippet:

    • h1, p, and div are the selectors that target the <h1>, <p>, and <div> elements.
    • color, font-size, border, background-color, width, and text-align are the properties.
    • #36CFFF, 1.5em, white, 5px inset gold, black, 300px, and center are the corresponding values passed to these properties.

    For a quick glance of CSS properties and features, check our CSS Reference page.

    Getting Started with CSS

    Below listed topics are most important to learn in CSS from basics to advance, after completing these topics you will able to style your HTML document as you want. We highly recommend you to do practice with CSS by modifying the provided code in this tutorial.

    CSS Basics

    Understanding the basics is important whenever you are learning something new. So before diving deep into CSS please know fundamentals of CSS.

    • CSS Introduction
    • CSS Syntax
    • CSS Selectors
    • CSS Inclusion
    • CSS Comments

    CSS Properties

    CSS properties and selectors are the main thing in CSS, without the properties there is no ways to define the styling of any HTML element. So better to know most frequently used properties in one go will help you to work with CSS.

    • CSS Background
    • CSS Border
    • CSS Display
    • CSS Float
    • CSS Font
    • CSS Line Height
    • CSS Margin
    • CSS Opacity
    • CSS Overflow
    • CSS Padding
    • CSS Position
    • CSS Align
    • CSS White Space
    • CSS Width
    • CSS Height
    • CSS Outline
    • CSS Visibility
    • CSS Counter

    You can get complete list of CSS Properties on the attached link.

    CSS Advanced

    After completing the above two section you can proceed with the advance part of this tutorial, these topics will helps you to make an actual website layout.

    • CSS Animation
    • CSS Gradient
    • CSS Transition
    • CSS Tooltips
    • CSS Arrow
    • CSS Grid
    • CSS FlexBox
    • CSS Responsive Design
    • CSS @Media Query
    • CSS 2D Transforms
    • CSS 3D Transforms
    • CSS Pseudo Classes

    CSS Practice

    The following are some of the important links to practice CSS:

    • CSS Interview Questions
    • CSS Online Quiz
    • CSS Online Test
    • CSS Mock Test
    • CSS Cheatsheet

    Prerequisites to Learn CSS

    Before using CSS extensively, it is essential to have a baisc understanding of the following prerequisites:

    • HTML – A fundamental understanding of HTML markup is necessary. This includes knowledge of HTML elements, attributes, tags, and their hierarchical structure.
    • Text Editors or Integrated Development Environments (IDEs) – In order to write to write your CSS code, a text editor or an IDE is required. Popular choices include Visual Studio Code, Sublime Text, Atom, or integrated editors within IDEs like IntelliJ IDEA or Eclipse.
    • Browser Developer Tools – Familiarizing yourself with browser developer tools can help you understand how styles are applied and troubleshoot layout issues.
    • Basic Environment Setup – Basic understanding of creating and managing files, along with saving and organizing them on your computer.

    If you are new to HTML and XHTML, then we would suggest you to go through our HTML or XHTML Tutorial first.

    Target Audience: Who Should Learn CSS?

    This tutorial has been prepared for beginners and professionals to help them understand the basics to advanced concepts of CSS. After completing this tutorial, you will find yourself at a great level of expertise in CSS, from where you can take your web design skills to the next level.

    Frequently Asked Questions about CSS

    There are some very Frequently Asked Questions(FAQ) about CSS, this section tries to answer them briefly.What is the Full form of CSS?

    chevron

    What is the purpose of CSS?

    chevron

    Is there any alternative of CSS?

    chevron

    What is the current version of CSS?

    chevron

    Is there any disadvantage of CSS?

    chevron

    Yes, CSS can’t provide maximum security, or you can say the purpose is not to provide that kind of security for your website. Lots of browsers required different properties for the same functionality(cross-browser issue).

  • Ruby Break Statement

    The Ruby break statement is used to terminate a loop. It is mostly used in while loop where value is printed till the condition is true, then break statement terminates the loop.

    The break statement is called from inside the loop.

    Syntax:

    1. break  

    Example:

    1. i = 1   
    2. while true   
    3.     if i*5 >= 25   
    4.         break   
    5.     end   
    6.     puts i*5   
    7.     i += 1   
    8. end   

    Output:

    Ruby Break 1

    Ruby Next Statement

    The Ruby next statement is used to skip loop’s next iteration. Once the next statement is executed, no further iteration will be performed.

    The next statement in Ruby is equivalent to continue statement in other languages.

    Syntax:

    1. next  

    Example:

    1. for i in 5…11   
    2.    if i == 7 then   
    3.       next   
    4.    end   
    5.    puts i   
    6. end  

    Output:

    Ruby Break 2
  • Ruby Comments

    Ruby comments are non executable lines in a program. These lines are ignored by the interpreter hence they don’t execute while execution of a program. They are written by a programmer to explain their code so that others who look at the code will understand it in a better way.

    Types of Ruby comments:

    • Single line comment
    • multi line comment

    Ruby Single Line Comment

    The Ruby single line comment is used to comment only one line at a time. They are defined with # character.

    Syntax:

    1. #This is single line comment.  

    Example:

    1. i = 10  #Here i is a variable.   
    2. puts i  

    Output:

    Ruby Comments 1

    The Ruby multi line comment is used to comment multiple lines at a time. They are defined with =begin at the starting and =end at the end of the line.

    Syntax:

    1. =begin  
    2.     This  
    3.     is  
    4.     multi line  
    5.     comment  
    6. =end  

    Example:

    1. =begin   
    2. we are declaring   
    3. a variable i   
    4. in this program   
    5. =end   
    6. i = 10   
    7. puts i  

    Output:

    Ruby Comments 2

  • Ruby Case Statement

    In Ruby, we use ‘case’ instead of ‘switch’ and ‘when’ instead of ‘case’. The case statement matches one statement with multiple conditions just like a switch statement in other languages.

    Syntax:

    1. case expression  
    2. [when expression [, expression …] [then]  
    3.    code ]…  
    4. [else  
    5.    code ]  
    6. end  

    Example:

    1. #!/usr/bin/ruby   
    2. print “Enter your day: ”   
    3. day = gets.chomp   
    4. case day   
    5. when “Tuesday”   
    6.   puts ‘Wear Red or Orange’   
    7. when “Wednesday”   
    8.   puts ‘Wear Green’   
    9. when “Thursday”   
    10.   puts ‘Wear Yellow’   
    11.  when “Friday”   
    12.   puts ‘Wear White’   
    13.  when “Saturday”   
    14.   puts ‘Wear Black’   
    15. else   
    16.   puts “Wear Any color”   
    17. end   

    Output:

    Ruby switch 1

    Look at the above output, conditions are case sensitive. Hence, the output for ‘Saturday’ and ‘saturday’ are different.

  • Features of Ruby

    Ruby language has many features. Some of them are explained below:

    Features of Ruby
    • Object-oriented
    • Flexibility
    • Expressive feature
    • Mixins
    • Visual appearance
    • Dynamic typing and Duck typing
    • Exception handling
    • Garbage collector
    • Portable
    • Keywords
    • Statement delimiters
    • Variable constants
    • Naming conventions
    • Keyword arguments
    • Method names
    • Singleton methods
    • Missing method
    • Case Sensitive
  • Ruby Cheatsheet

    The Ruby Cheatsheet provides the fundamentals of Ruby programming. It helps students and developers to build the projects and prepare for the interviews. Go through the cheat sheet and learn the concepts. Thus, this improves the coding skills.

    • Basic Syntax
    • Variables
    • Operators
    • Comments
    • String
    • String Interpolation
    • If-else Statement
    • Classes and Objects
    • Break Statements
    • Ruby Blocks
    • Modules
    • Array
    • Hashes
    • Ranges
    • Regular Expression
    • Exception Handling
    • Commonly Used Library

    1. Basic Syntax

    This is the basic syntax of the Ruby programming language that displays the text using puts and print.

    puts "Hello, World!"
    print "Tutorialspoint!"

    2. Variables

    Variables are used for the memory location. Ruby supports various types of variable −

    # Defining the variables
    x =10# integer
    y =20.5# float
    puts x + y
    

    3. Operators

    The operators are the symbol that tells the compiler to perform logical tasks.

    OperatorsDescriptionExample
    Arithmetic OperatorsThis is basic mathematical operations.‘a + b’, ‘a – b’, ‘a * b’, ‘a / b’, ‘a % b’
    Relational OperatorsThis compares two values.‘a == b’, ‘a != b’, ‘a > b’, ‘a < b’, ‘a >= b’, ‘a <= b’
    Logical OperatorsThis combine the conditional statements.‘a && b’, ‘a || b’, ‘!a’
    Bitwise OperatorsThis perform in the bit level.‘a & b’, ‘a | b’, ‘a ^ b’, ‘~a’, ‘a << b’, ‘a >> b’
    Assignment OperatorsThis assign the values to the variables.‘a = b’, ‘a += b’, ‘a -= b’, ‘a *= b’, ‘a /= b’, ‘a %= b’

    Below are the some examples of operators in Ruby programming language −

    # Arithmetic Operators# Addition
    puts 8+18# Subtraction  
    puts 9-3# Multiplication  
    puts 7*6# Division
    puts 20/4# Comparison Operators# Greater than
    puts 10>5# Equal to  
    puts 10==5# Not equal to
    puts 10!=5

    4. Comments

    Comments are used to show the information. The single-line comment is denoted by “#” whereas multi-line comments are written using the =begin and =end keywords.

    # This is a single-line comment=begin
    multi-line comment
    =end

    5. String

    The strings are used to print the text. In Ruby, strings are represented using both single and double quotes.

    # Strings
    str1 ="Hello"
    str2 ='World!'
    puts str1 +" "+ str2
    

    6. String Interpolation

    The string interpolation is the process of inserting the values with the help of expression inside the curly braces #{}.

    name ="Tutorialspoint!"
    puts "Welcome to #{name}!"

    7. If-else Statement

    The if-else statement is a part of the control structure used to execute the logic conditionally, based on whether the condition is true or false.

    age =18if age >=18
      print "You are eligible for vote."else
      print "You are are not eligible for vote."end

    8. Classes and Objects

    Classes and objects are fundamental concepts of object-oriented programming. A class defines the blueprint for an object, whereas an object is an instance of a class.

    classPersondefinitialize(name, id)@name= name
    
    @id= id
    enddeffun
    puts "My name is #{@name} and I am #{@id} years old."endend
    person =Person.new("Sanjay",25) person.fun

    9. break Statements

    In Ruby, the break statement terminates the program loop.

    num =[1,2,3,4,5,6,7,8,9,10]
    num.eachdo|num|if num ==7
    
    puts "The loop break at the number #{num}"breakend
    puts "The processing number is #{num}"end puts "Loop ended."

    10. Ruby Blocks

    The blocks represent the anonymous function in Ruby that is passed into the methods. The block can be declared using a single-line or multi-line block.

    times { puts "Hello, Block!"}

    11. Modules

    In Ruby, a module is a collection of methods and constants that can be used to organize and structure code.

    # example of modulesmoduleMathHelpersdefsquare(x)
    
    x * x
    endendincludeMathHelpers puts square(4)

    12. Array

    In Ruby, an array defines the ordered, indexed collection of objects. The object holds the data types such as String, Integer, Fixnum, Hash, Symbol, and even other Array objects.

    arr =[10,20,30,40,50]
    arr.each{|i| puts i }

    13. Hashes

    The hashes are similar to dictionaries by defining key−value pairs.

    hash ={ name:"Ruby", id:3323}
    puts hash[:name]

    14. Ranges

    The ranges are data types that show a sequence of values.

    (1..5).each{|i| puts i }

    15. Regular Expression

    Regular Expression is defined by the special sequence of characters that help users to find the set of string matches or particular syntax held in the program.

    /pattern//pattern/im# option can be specified%r!/usr/local!# general delimited regular expression

    16. Exception Handling

    In Ruby, an exception handling is the process of handling the error raised in the program. These errors occur during the execution of the program. In simple, unexpected, or unwanted events.

    beginraise# block where exception raiserescue# block where exception rescueend

    17. Commonly Used Library

    Here, we are providing the example of the JSON library.

    require'json'
    data ={ name:"Ruby", type:"Programming Language"}
    puts JSON.generate(data)