besides `%w[1 2 3]` what other methods or tricks exist that use % then some letter? in ruby

In Ruby, besides %w which is used to create an array of strings, there are several other notations that use the % character followed by a letter. Here are some of them:

  1. %q or %Q: These notations are used to create a single-quoted or double-quoted string, respectively. They are useful when you have a string that contains many special characters and you want to avoid escaping them. For example:

    main.rb
    puts %q(You don't need to escape single quotes in this string)
    puts %Q(You can include double quotes "here" without escaping them)
    
    131 chars
    3 lines
  2. %r: This notation is used to create a regular expression. It allows you to define a regular expression pattern without the need for explicitly using the Regexp.new constructor. For example:

    main.rb
    pattern = %r(\d{3}-\d{3}-\d{4})
    puts "Valid phone number" if "555-123-4567" =~ pattern
    
    87 chars
    3 lines
  3. %s: This notation is used to create a symbol, which is a lightweight constant in Ruby. It is similar to a string but immutable and unique. For example:

    main.rb
    my_symbol = %s(foo)
    puts my_symbol #=> :foo
    
    44 chars
    3 lines
  4. %i or %I: These notations are used to create an array of symbols. %i creates symbols without interpolation, while %I allows for interpolation. For example:

    main.rb
    name = "Alice"
    symbols = %i[hello #{name} goodbye]
    puts symbols #=> [:hello, :"\#{name}", :goodbye]
    
    100 chars
    4 lines

These notations provide a convenient way to create certain types of objects in Ruby. They are especially helpful when you have strings or patterns that contain characters that would normally require escaping.

related categories

gistlibby LogSnag