ruby , How to handle backslash “\” escape characters in q string and heredocument

## Question:

Tag: ruby

Ruby Newbie here. I do not understand why Ruby looks inside %q and escapes the \.

I am using Ruby to generate Latex code. I need to generate \\\hline which is used in Latex for table making. I found \\\hline as input generated \hline even though the string was inside %q.

Here is MWE

#!/usr/local/bin/ruby -w
tmp = File.open('foo.txt','w')
str = %q[\\\hline]
tmp.write(str)
tmp.close


The file foo.txt has this

 \\hline


Ruby does give the warning

   warning: encountered \r in middle of line, treated as a mere space


But this should not be generated since this is supposed to be escaped strings?

Now I tried it with Python multiline raw strings (similar to Ruby's %q)

file = open('foo4.txt', 'w')
str = r"""\\\hline"""
file.write(str)
file.close()


And the file again contains \\\hline as expected.

Am I doing something wrong in Ruby?

ruby -v
ruby 2.2.2p95 (2015-04-13 revision 50295) [i686-linux]


Answer:
str = <<'TEXT'
hello %s
\\\hline
%s
TEXT

name = "Graig"
msg = "Goodbye"
puts str % [name, msg]


The heredoc does not have escape chars when it's delimiter is in single quotes. It does have a form of interpolation. The code above has this output:

hello Graig
\\\hline
Goodbye


More fancy is using a hash for interpolation:

str = <<'TEXT'
hello %{name}
\\\hline
%{msg}, %{name}
TEXT

puts str % {name: "Graig", msg: "Goodbye"}


Output:

hello Graig
\\\hline
Goodbye, Graig


# Related:

## Heroku rake db:migrate failing - uninitialized constant

ruby-on-rails,ruby,heroku
My app is working fine locally and my push to Heroku was successful. But, when I run heroku run rake db:migrate, I get the following error: NameError: uninitialized constant AddWeightToExercises Here is the failed migration: class AddWeightToExercise < ActiveRecord::Migration def change add_column :exercises, :weight, :float end end edit: Thanks for...

## Rails - link_to path based on object's name + refactoring multiple custom actions

ruby-on-rails,ruby,refactoring
I'm looking to simplify the link_to path based on thr object's name and also am looking into refactoring multiple custom actions. I've managed to get this working below. <% ServiceMenu.all.each do |menu| %> <tr class=" <%= cycle('odd', 'even') %>"> <td><%= link_to menu.name, ("tech/""#{menu.name.parameterize}") %></td> </tr> <% end %> I feel...

## How to pivot array into another array in Ruby

arrays,ruby,csv
I have a multidimensional array like this one : myArray = [["Alaska","Rain","3"],["Alaska","Snow","4"],["Alabama","Snow","2"],["Alabama","Hail","1"]] I would like to end up with CSV output like this. State,Snow,Rain,Hail Alaska,4,3,nil Alabama,2,nil,1 I know that to get this outputted to CSV the way I want it I have to have output array like this: outputArray =[["State","Snow","Rain","Hail"],["Alaska",4,3,nil],["Alabama",2,nil,1]]...

## Get value from string representing local variable [duplicate]

ruby,local-variables
This question already has an answer here: Is there a 'variable_get' method? If not, how can I create my own? 2 answers I have a local variable name as a string, and need to get its value. variable = 22 "variable".to_variable? How can I get the value 22 form...

## Rails less url path change

ruby-on-rails,ruby,url,path,less
Developing a Rails application with the less-rails gem I found something unusual : // app/assets/common/css/desktop/typo.less @font-face{ font-family:'SomeFont'; src:url("fonts/db92e416-da16-4ae2-a4c9-378dc24b7952.eot?#iefix"); // ... } The requested font is app/assets/common/css/fonts/db92e416-da16-4ae2-a4c9-378dc24b7952.eot This font is compiled with less and the results is : @font-face { font-family: 'SomeFont'; src: url("desktop/fonts/db92e416-da16-4ae2-a4c9-378dc24b7952.eot?#iefix"); //... } Do you know why is...

## Undefined local variable post

ruby-on-rails,ruby,variables,undefined,local
I write this code: <% @user.posts.each do |post| %> <%= render 'post', locals: { post: post, user: @user} %> <% end %> Then in _post.htm.erb I write follow code: <div class="post-title"> <img src="<%= @user.avatar.url%>" class="img-rounded post-image"> <h4 id="post-name"><%= @user.first_name + ' ' [email protected]_name %> </h4> <div id="post-date"><%= post.created_at.strftime('%d %b -...

## Ruby boolean logic: some amount of variables are true

ruby
Let say I have 3 variables: a, b, c. How can I check that just zero or one of them is true?...

## Appending an element to a page in VoltRb

html,ruby,opalrb,voltrb

## What is Rack::Utils.multipart_part_limit within Rails and what function does it perform?

ruby-on-rails,ruby,rack,multipart
Rack::Utils.multipart_part_limit is set to 128 by default. What purpose does the value have and what effect does it have within the Rails system?...

## Rails basic auth not working properly

ruby-on-rails,ruby,authentication
I am building a small API that uses basic authentication. What I have done, is that a user can generate a username and password, that could be used to authenticate to the API. However I have discovered that it is not working 100% as intended. It appears that a request...

## regex to pull in number with decimal or comma

ruby,regex
This is my line of code: col_value = line_item[column].scan(/\d+./).join().to_i When I enter 30,000 into the textfield, col_value is 30. I want it to bring in any number: 30,000 30.5 30.55 30000 Any of these are valid... Is there a problem with the scan and or join which would cause it...

## Ruby on Rails - Help Adding Badges to Application

ruby-on-rails,ruby,rest,activerecord,one-to-many
I'm creating a rails application that is a backend for a mobile application. The backend is implemented with a RESTful web API. Currently I am trying to add gamification to the platform through the use of badges that can be earned by the user. Right now the badges are tied...

## In Ruby how to put multiple lines in one guard clause?

ruby-on-rails,ruby
I have the following line of code : if params[:"available_#{district.id}"] == 'true' @deliverycharge = @product.deliverycharges.create!(districtrate_id: district.id) delivery_custom_price(district) end Rubocop highlight it and asks me to use a guard clause for it. How can I do it? EDIT : Rubocop highlighted the first line and gave this message Use a guard...

## RSpec test for rake task

ruby-on-rails,ruby,rspec,rake-task
I have created a custom rake task that deletes all items that are >= 7 days old. I am trying to write a RSpec test for this new task but it seems like my task isn't really running in the test. I have tested the task manually and it works...

## Dividing by half in ruby to create an effective calculator

ruby,calculator
For the past while I've been working on a calculator, but have run into problems when needing to divide by a half. I'll add the offending bit of code along with a loop to keep it open below. on = true while on == true do half = 1.0 /...

## Split an array into slices, with groupings

arrays,ruby,enumerable
I've got some Ruby code here, that works, but I'm certain I'm not doing it as efficiently as I can. I have an Array of Objects, along this line: [ { name: "foo1", location: "new york" }, { name: "foo2", location: "new york" }, { name: "foo3", location: "new york"...

## How to flatten a structure of embedded Set and Hash

ruby,recursion
I would like to convert an embedding structure into a flat one. An embedding structure is a set of 0 or more objects, such as: a string or a hash having some string as key and some other embedding structure as value. A flat structure is a set of arrays...