# Copying values from a different file into variables

**URL:** <https://www.ruby-forum.com/t/copying-values-from-a-different-file-into-variables/173918>\
**Category:** Ruby\
**Created:** [August 18, 2009, 9:23am UTC](https://www.ruby-forum.com/t/copying-values-from-a-different-file-into-variables/173918 "2009-08-18T09:23:39Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![shekarls](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/c68b51/32.png) [@shekarls](https://www.ruby-forum.com/u/shekarls)\
**Post date:** [August 18, 2009, 9:23am UTC](https://www.ruby-forum.com/t/copying-values-from-a-different-file-into-variables/173918/1 "2009-08-18T09:23:39Z")

</div>

I would like to copy specific lines(contents) from file1 into file2.

# File1 has following information:

browser = “firefox”  
id = “removed\_email\_address@domain.invalid”  
password= “12345678”  
account = “Yes”

# I want the following information in File2 :

@var1 = “firefox” (value of browser from File1)  
@var2 = “removed\_email\_address@domain.invalid” (value of id from File1)  
@var3 = “12345678” (value of password from File1)

How do i get this done using ruby. Please let me know if you require  
more clarification on this front.

Cheers

---

<div class="post-metadata">

**Author:** ![shekarls](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/c68b51/32.png) [@shekarls](https://www.ruby-forum.com/u/shekarls)\
**Post date:** [August 19, 2009, 12:30pm UTC](https://www.ruby-forum.com/t/copying-values-from-a-different-file-into-variables/173918/2 "2009-08-19T12:30:31Z")

</div>

On Aug 18, 2009, at 10:23 AM, Shekar Ls wrote:

> I would like to copy specific lines(contents) from file1 into file2.

You’d generally get more help if you try to do some of the work and  
then post if/when you get stuck.

> @var1 = “firefox” (value of browser from File1)  
> @var2 = “removed\_email\_address@domain.invalid” (value of id from File1)  
> @var3 = “12345678” (value of password from File1)
> 
> How do i get this done using ruby. Please let me know if you require  
> more clarification on this front.

I haven’t used ruby that long but something like

File.open(“file2”, “w”) do |f2|  
count = 1  
File.foreach(“file1”) do |line|  
f2 \<\< line.sub(/^[\w\s]+=/, “@var#{ count } =”)  
count += 1  
end  
end

could work. (skipping the creation of @var4 for the “account” line is  
left as an exercise for the OP)
