变量变化

发布于 2024-12-11 23:51:23 字数 595 浏览 0 评论 0原文

我编写了一些代码来获取用户的输入,然后根据我的需要进行更改。我需要它的改变和未改变的形式,所以我将输入保存到两个变量中。我不明白的是为什么这两个变量都在变化。我尝试了一些额外的 put 行来确定原因是什么,但我无法弄清楚。代码:

puts "Enter the full directory path of the flv files."
folder = gets.chomp
puts "Folder 1: " + folder
path = folder
path.slice!(0..6)
path.gsub!('\\', '/')
path += '/'
puts "Folder: " + folder
puts "Path: " + path

输入:f:\folder\subfolder\another

输出:

Folder 1: f:\folder\subfolder\another 
Folder: folder/subfolder/another
Path: folder/subfolder/another/

我想要获取一个目录并为其他进程保留该目录,同时将其转换为 URL 友好的格式。有想法吗?

I wrote some code to get input from a user and then alter it to my needs. I need it in the altered and unaltered form so I am saving the input into two variables. What I don't understand is why it both variables are changing. I tried some extra puts lines to determine what the cause is but I am unable to figure it out. The code:

puts "Enter the full directory path of the flv files."
folder = gets.chomp
puts "Folder 1: " + folder
path = folder
path.slice!(0..6)
path.gsub!('\\', '/')
path += '/'
puts "Folder: " + folder
puts "Path: " + path

With input: f:\folder\subfolder\another

Output:

Folder 1: f:\folder\subfolder\another 
Folder: folder/subfolder/another
Path: folder/subfolder/another/

What I'm going for is getting a directory and keeping the directory for other processes, but also transforming it into a URL friendly format. Ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

像你 2024-12-18 23:51:23
path = folder # does not actually copy the object, copies the reference
path.object_id == folder.object_id # the objects are the same, see
path.slice!(0..6) # all bang methods work with the same object

因此,您的路径是对与文件夹相同的对象的引用。

要解决此问题,请使用

path = folder.clone
path = folder # does not actually copy the object, copies the reference
path.object_id == folder.object_id # the objects are the same, see
path.slice!(0..6) # all bang methods work with the same object

Thus your path is a reference to the same object as folder.

To fix this, use

path = folder.clone
挥剑断情 2024-12-18 23:51:23

当您执行 b = a 时,它会使 b 指向与 a 相同的值,因此当您更改 a 时使用诸如 slice! 之类的 > 的值,b 也将指向更改后的值。

为了避免这种情况,请复制该对象:

b = a.dup

When you do b = a, it's making b point at the same value as a, so when you change a's value using something like slice!, b will also point to the changed value.

To avoid this, duplicate the object instead:

b = a.dup
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文